Thread safe singleton class to connect to Cassandra

First thoughts

Before even commenting the code, I have to say that the intent of this class is for me totally obscure. When I encounter some xxxUtil class, I expect to find some static utility methods. However here, it isn't the case.

Second, I'm not sure that I understand why you make this class a singleton. Yes, everytime I see a singleton I challenge that because it is very likely that it is an anti-pattern. So I will ignore the singleton for the rest of my answer.

Purpose of this class

The next thing that bothers me is that I'm not able to find the purpose of this class. It has no behaviour (except maybe shutdown()) ! All you do is creating two objects (session and cluster) and returning them. So the internal state of this class has totally leaked out (via getSession() and getCluster()) and all the work done with these two object is done outside of CassUtil, which is a significant smell in OOP world.

More concretely

Leaving these "philosophical" aspects above, let's dig a bit in something more concrete, the code itself.

Immutability

Making things immutable always help to get a more maintainable code, therefore I would advice to make CassUtil final so that noone can break it by subclassing. I would also make session and cluster final so that it becomes clear for anyone reading your code that once you instanciated them, they won't change anymore.

public final class CassUtil {
    private final Session session;
    private final Cluster cluster;

PoolingOptions

Does these two lines really do something useful other than assigning an existing value to itself ?

PoolingOptions opts = new PoolingOptions();
opts.setCoreConnectionsPerHost(HostDistance.LOCAL,opts.getCoreConnectionsPerHost(HostDistance.LOCAL));

If not, you can just remove these lines and do

.withPoolingOptions(new PoolingOptions())

StringBuilder

At the end of the constructor, you iterate through all hosts and append some content in a StringBuilder just to add it in a log statement. Wouldn't it be enough to do something like that ? (or equivalent)

LOGGER.logInfo("CONNECTED SUCCESSFULLY TO CASSANDRA CLUSTER: " + cluster.getClusterName());

Thus removing the need for the whole block constructing the StringBuilder:

StringBuilder sb = new StringBuilder();
Set<Host> allHosts = cluster.getMetadata().getAllHosts();
for (Host host : allHosts) {
    sb.append("[");
    sb.append(host.getDatacenter());
    sb.append(host.getRack());
    sb.append(host.getAddress());
    sb.append("]");
}

Get rid of TestUtils

I notice that your code depends a lot on TestUtils, which is static. And static means that your class is really hard to test. Let me reiterate: static dependencies make your class really (if not impossible) hard to test.

TestUtils provides 4 things:

Hostnames
A username
A password
Indirectly, a localDc

You better take all of these as arguments in the constructor, so that you don't need to reference TestUtils directly.

public CassUtil(List<String> servers, String username, String password, String localDc) {
    ...
}

This line

!TestUtils.isProduction() ? "DC2" : TestUtils.getCurrentLocation().get().name().toLowerCase()

is really the biggest smell of all these four because you actually mixed some production and testing concepts in the same place. That's why I advised you to take directly the localDc in argument instead of a boolean isProduction.

Creating the session

I'm not sure it makes sense here to embed the session's creation inside a try/catch. I would just remove it and let the exception bubble up, if ever. If you think it's probable exceptions will be raised from this call, then this instruction doesn't belong to the constructor, but should rather be in the method(s) where session is used (or in a connect() method, which would be the counterpart of shutdown()). So instead of

try {
    session = cluster.connect("testkeyspace");
    LOGGER.logInfo("CONNECTED SUCCESSFULLY TO CASSANDRA CLUSTER: " + cluster.getClusterName());
} catch (NoHostAvailableException ex) {
    LOGGER.logError("error= ", ExceptionUtils.getStackTrace(ex));
} catch (Exception ex) {
    LOGGER.logError("error= " + ExceptionUtils.getStackTrace(ex));
}

Just do

session = cluster.connect("testkeyspace");
LOGGER.logInfo("CONNECTED SUCCESSFULLY TO CASSANDRA CLUSTER: " + cluster.getClusterName());

Something that raised a warning in my head is the hardcoded string "testkeyspace". I suspect that this name should be different if you try to create a session in production or in testing. If so, you also need to take this string in the constructor's argument.

Remove null checks

Since now session and cluster are final, it is guaranteed that they won't ever be null. shutdown() and getSession() thus become:

public void shutdown() {
    LOGGER.logInfo("Shutting down the whole cassandra cluster");
    session.close();
    cluster.close();
}

public Session getSession() {
    return session;
}

Usage

Now that the constructor has changed (taking now 5 arguments) you might ask how to construct instances of CassUtil ?

For testing purpose:

new CassUtil(TestUtils.HOSTNAME, TestUtils.USERNAME, TestUtils.PASSWORD, "DC2", "testkeyspace");

In production:

new CassUtil(/*some real server names*/, /*username of current user*/, /*password of current user*/, /*name of the production local datacenter*/, /*production keyspace*/);

Conclusion

This is the whole class with all of these remarks:

import java.util.List;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PoolingOptions;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;

public final class CassUtil {
    private static final Logger LOGGER = Logger.getInstance(CassUtil.class);
    private final Session session;
    private final Cluster cluster;

    public CassUtil(List<String> servers, String username, String password, String localDc, String keyspace) {
        cluster = Cluster.builder().addContactPoints(servers.toArray(new String[servers.size()]))
                                   .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)
                                   .withPoolingOptions(new PoolingOptions())
                                   .withReconnectionPolicy(new ConstantReconnectionPolicy(100L))
                                   .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(localDc)
                                                                                .withUsedHostsPerRemoteDc(3)
                                                                                .build())
                                   .withCredentials(username, password)
                                   .build();
        session = cluster.connect(keyspace);
        LOGGER.logInfo("CONNECTED SUCCESSFULLY TO CASSANDRA CLUSTER: " + cluster.getClusterName());
    }

    public void shutdown() {
        LOGGER.logInfo("Shutting down the whole cassandra cluster");
        session.close();
        cluster.close();
    }

    public Session getSession() {
        return session;
    }

    public Cluster getCluster() {
        return cluster;
    }
}

Now your class looks more clean but also presents the terrible signs of anemia (as expressed in the first two chapters of this answer) ! Think about that class: "which services should this class offer ?". Unfortunately, I can't answer that for you. But I'm sure as soon as you find the answer you will be able to find it a better name and add it new methods that actually contains business logic.


You have redundant parentheses here: (y > x && y > z). You can also make your type more generic: localMaxima :: Ord a => [a] -> [a].

I think it looks a bit cleaner using an as-pattern and guard clauses. This way you don't need zs and can just write _.

localMaxima (x:rest@(y:z:_))
  | y > x && y > z = y : localMaxima rest
  | otherwise      = localMaxima rest
localMaxima _ = []

In fact, if you know that y > z then you don't need to check if z is a local maximum.


How can I make handling multiple {}.get('value', {}.get('foo')) pretty?

Your code attempts to fetch the values of all keys when it probably only really needs one.  You do not want to be doing this.

I think it would be better to create a list representing the priorities of what values you wish to retrieve and attempt to retrieve them.

def get_value(priorities):
    for key, dictionary in priorities:
        try:
            return dictionary[key]
        except KeyError:
            pass
    return None

priorities = [
    ('foo', dictionary1),
    ('bar', dictionary1),
    ('baz', dictionary2),
]
foo = get_value(priorities)


I will have to admit I personally prefer the First attempt, but both seem like they would run fast and deliver as expected.

The only piece I don't like so much, which is found in both attempts, is this:

    select g + f * 2 + e * 4 + d * 8
    + c * 16 + b * 32 + a * 64 as n

I think this could really use some parentheses for clarity, if nothing else.

    select (
    g + (f * 2) + (e * 4) + (d * 8)
    + (c * 16) + (b * 32) + (a * 64)
    ) as n


Simple, flexible, and thread-safe key/value memory cache

Generally, the code is simple and easy to understand.

Concurrency

It's good that you have a dedicated Lock object. You might consider a more expressive name, but in this case I think you can get away with it.

As you have noticed, using the lock means you gain nothing from the ConcurrentDictionary'2. Since this is such a simple interface, I would keep the lock and ditch the ConcurrentDictionary unless you have a serious (and measurable) performance concern.

However, you should be aware that by locking while you call Set, you are blocking access while you wait for an operation to complete, the length of which you cannot know. Addressing this without changing the class' behaviour would be non-trivial, primarily because it would complicate the case where Set fails, but may be necessary if Set is slow or needs access to the cache itself. If you don't care how many times you call Set, you could just use ConcurrentDictionary.GetOrAdd as mentioned by CharlesNRice in a comment, which would simply things somewhat.

Other

It's good that you have provided some level of inline documentation. I would be inclined to add an explanation of the threading behaviour (e.g. blocks while calling Set, will only call Set once). "a thread-safe way" is pretty meaningless: it's much better to explain the guarantees you will make.
Do you anticipate needing to change Set? If not, you should consider making it readonly and assign it in a constructor. There is a design concern that changing Set means you can't know which version was used by any call to Get from another thread.
Using a Tuple<int?, string> as a union doesn't seem a great idea. Either implement a sound union as a class of struct, or consider having a separate cache for each. If you do wish to keep this API, you should enforce the assumption that exactly one of them is null by explicitly checking and throwing if this is not the case, since it represents an error on the part of the caller, and telling them them sooner rather than later will save them lots of misery and time spent debugging.


Creating an image in Excel using the colors from an input image

AFAIR, styles are "heavy cost" objects in the workbook. Thus, create each XSSFCellStyle only once and reuse the XSSFCellStyle object for the same color.


Does the class have unnecessary and violating Single responsibility principle method?

You're right, but you should take this to its logical conclusion.

Creating item belongs to a factory class.
Tracking a list of items (coordinating?) is another responsibility.
Handling the new item (or list? Not clear from the code) belongs to a third class.

With this design you can reliability test each component in isolation. Merging these responsibilities into a single class makes testing difficult and blocks alternate implementations.


Split CSV file into a text file per row, with whitespace normalization

It seems odd, right now, that you throw away the document_id, and that's at least worth an explanatory comment.

The code that transforms each document — the whitespace processing — should be moved into a separate function. This because it is a distinct operation from the CSV reading, and allows it to be separately unit tested.

The code needs to handle the header row from the input.

If by "better" you are asking for faster, well for that you could split up the input file and run multiple copies of your program (and changing how output filenames are generated, since the line numbers wouldn't be the same).


if (box.left > 0) {
    if (box.left >= window.innerWidth) {
        return false;
    }
}

This seems a little redundant: the innerWidth is going to be greater than 0, so why do you need to conditionals?

Simply remove the outer one.

Your conditions are fairly short. Consider combining them:

if (box.right <= 0 || box.bottom <= 0) {
    return false;
}

if (box.left >= window.innerWidth || box.top >= window.innerHeight) {
    return false;
}

There isn't much more to say about your code, but I have an idea for future improvement: right now, your code will say true even if the element is partially hidden on the screen. How do you plan on handling this?


Sentinel based find with conditional fallback to std::find

std::integral_constant<bool, std::is_nothrow_copy_assignable<std::remove_reference_t<decltype(*first)> >::value>

is a very complicated synonym for

std::is_nothrow_copy_assignable_t<std::remove_reference_t<decltype(*first)>>

in this context, because all the UnaryTypeTraits are defined by the standard to be "publicly and unambiguously derived" (directly or indirectly) from their BaseCharacteristic of std::true_type or std::false_type.

Your code returns std::prev(last) when *last == value, even if there's an instance of value prior to that in the sequence. This isn't a bug (presumably), but it's surprising enough that you should probably document it explicitly somewhere; otherwise I'd assume a function named find to have semantics exactly the same as std::find [alg.find] — i.e., "return an iterator to the first matching element".

Checking is_nothrow_copy_assignable<...> doesn't really buy you anything, if you aren't going to check is_nothrow_copy_constructible<...> and is_nothrow_equality_comparable<...> and is_nothrow_prefix_incrementable<...>... and so on, for all the other operations you do inside the "critical section" of your function (between the line where you blow away the old value of *real_last and the line where you restore it).

Alternatively, you could use a try/catch to make sure that you always restore the old value of *real_last. Since C++ lacks the "finally" construct that exists in languages such as Java and Python, I recommend a generic scope-guard construct such as Auto() if you find yourself doing this kind of thing very often.

Your code has a problem with empty ranges.


Represent a Class which holds translation Strings

You haven't given much context about how you intend to use this class, which is always important.  In my experience (echoed in comments), there's not much use case for needing all translations of a string at one time.  The use case is more typically that you need to render the UI in a particular language, so you need a bunch of German strings but none of the other languages.  Also, you want to be able to easily add support for additional languages, ideally without any code changes.  That's what resource bundles are for, it seems like you are trying to reinvent the wheel here.  If you think that resource bundles don't solve your problem, you should give more context.


I'm not sure if this is a programming exercise or an excel exercise, or a programming in excel exercise. Each will have a different answer. But I can give you a few answers to start.

As a first comment. You are right, setting and getting values into excel cells one at a time is not desirable if you can do it in a large chunk.

Lets put a few tools into place.

The type of collection you are wanting to use to collect data is called a dictionary. You can use the dictionary provided in microsoft using the reference "Microsoft Scripting Runtime" the scrrun.dll. This will give you a key value pair to be able to do ..

Dim toolsDictionary As Dictionary
Set toolsDictionary = New Dictionary
...

If Not toolsDictionary.Exists(nextItemName) Then
    toolsDictionary(nextItemName) = 0
End If

Next you'll need to be able to test if a value is a number. This will let you work out if the row you are on is of any value to you. Here you are dealing with excel, not vba.

WorksheetFunction.IsNumber(someVariable)

Then you can also make use of VBA's setter or letter. Given

Dim inputData as Variant
Set inputData = ws2.Range("a1").CurrentRegion   'setter
inputData = ws2.Range("a1").CurrentRegion       'letter

the value of inputData in the setter will be a range object, while the inputData in the letter will contain a 2D array.

Last little tool is an excel tool.

Range.Sort

Lets not bother with just the labels, but we'll copy the whole data set across, and sort it

ws1.Range("A:B").Copy Destination:=ws2.Range("A:b")
ws2.Range("a:b").Sort Key1:=ws2.Range("b1"), Header:=xlYes

Now we have a few useful tools, so we can get on with the job at hand. And just as a warning. This is excel, so there are lots of ways to do this. This is  a VBA way.

'get our data and sort
ws1.Range("A:B").Copy Destination:=ws2.Range("A:b")
ws2.Range("a:b").Sort Key1:=ws2.Range("b1"), Header:=xlYes

' load our data into an array
inputData = ws2.Range("a1").CurrentRegion
count = ubound(inputData)

' traverse our data
for counter = 1 to count

    ' is it a tool
    isATool = WorksheetFunction.IsNumber (inputData(counter, 2))
    If isATool Then

        theTool = inputdata(counter,1)
        theNumber = inputdata(counter,2)

        ' check if we have a record
        If Not toolsDictionary.Exists(theTool) Then
            toolsDictionary(theTool) = 0
        End If

        ' accumulate the totals
        toolsDictionary(theTool) = theNumber
        Debug.Print toolsDictionary(theTool)

Once you've got all your data, repopulate your inputData. Make sure we offset by 1 to keep our header.

ws2.range("a1:b1").CurrentRegion.Offset(1).clear

count = toolsDictionary.count

inputData = ws2.range("a2:b2").resize(count)
' you could do
' ReDim inputData(1 To 5, 1 To 2). But I don't like to.
for counter = 0 to count - 1    ' dictionary is zero based
     theTool = toolsDictionary.keys(counter)
     theNumber = toolsDictionary.items(counter)
     inputData(counter + 1, 1) = theTool
     inputData(counter + 1, 2) = theNumber
next counter

ws2.Range("a2:b2").Resize(counter,2).Value2 = inputData


Very Simple Spell (Number to Words) 001 to 999 in VBA

Code Formatting

What certainly could be improved is the indentation of your code for better readability:

Function Do999(ThreeDigits As String)
    'Everything after your function header until End Function should be indented
    ' ...
End Function

Same for further conditional code blocks:

N1 = Left(ThreeDigits, 1): N2 = Right(ThreeDigits, 2)
If N2 > 19 Then
    t = Tens(Val(Mid(ThreeDigits, 2, 1))) & dash & Ones(Val(Right(ThreeDigits, 1)))
Else
    t = Ones(N2)
End If

Do999 = Trim(IIf(N1 > 0, Ones(N1) & Tens(10), "") & " " & t)

Function naming

Do999 isn't very clear / self descriptive about what the function does.
Convert0UpTo999ToWords might be a better choice for example.

Number output in words

  The function uses the dash "-" for numbers e.g. Forty-Two.

That's not how numbers are naturally written in words. Usually 42 would be written as forty-two.

Avoid the 1st letter of the number words to be capitalized.


Best practice is to do away with cursors. Both of them. There is always a better-performing solution.

If possible, reduce the problem to one that can be solved with sets instead of iteration.

But, if this nested iteration cannot be avoided, you will still get far better performance using table variables and WHILE loops instead of a cursor. For example:

DECLARE @outerData TABLE (outerID INT, outerColumn VARCHAR(50), PRIMARY KEY (outerID))
DECLARE @innerData TABLE (innerID INT, innerColumn VARCHAR(50), PRIMARY KEY (innerID))
DECLARE @currOuter INT
DECLARE @currInner INT

INSERT INTO @outerData
SELECT  EmployeeID, EmployeeName
FROM dbo.Employee

WHILE EXISTS (SELECT outerID FROM @outerData)
BEGIN
    SELECT @currOuter = TOP outerID FROM @outerData

    INSERT INTO @innerData
    SELECT SaleID, SaleDesc
    FROM EmployeeSales
    WHERE EmployeeID = @outerID

    WHILE EXISTS (SELECT innerID FROM @innerData)
    BEGIN
        SELECT @currInner = TOP innerID FROM @innerData

        --Do work with inner data

        ...blah-de-blah...

        --Delete after work is finished
        DELETE FROM @innerData   WHERE innerID = @currInner
    END

    --Delete current outerID and empty the innerdata table
    --to prepare to move to the next record

    DELETE FROM @outerData WHERE outerID = @currOuter
    DELETE FROM @innerData
END


Calculate expiration date based on server data

General naming guidelines suggest that an async method should end its name with "Async", so the method name should be RevalidateAccountAsync.

Some would argue that a underscore prefix should never be used for naming of any variables.  For those that do allow underscore prefixes, it should only be for class-level variables and never used for variables local to a given method.

When comparing or manipulating 2 DateTime objects, the proper way to do that is to be sure that both have the same Kind.  Oddly enough, your code does that since you jump through so many hoops to create new DateTime objects with Kind of Unspecified.

expirationDate is a misleading name since it is not a date.  It is a TimeSpan.

After checking expirationDate.Days <= 7, there is no need to check IsVisibleValidateText since it will always be true at that point.

Your code looks to be twice as long as it needs to be because of all the manipulation of DateTime and string.  For example, to get today's date should only be 1 line:

DateTime todayDate = DateTime.Today; \\Kind is Local

expDate could use DateTime.Parse or Convert.ToDateTime.  However, you should also set it's Kind because as it is it will be Unspecified unless the string contains any time zone offset.  Example setting it to Local:

DateTime expDate = DateTime.SpecifyKind(Convert.ToDateTime(_expDateFromPersistent), DateTimeKind.Local);

The alternative would be to keep expDate as Unspecified but then make todayDate also Unspecified.

DateTime todayDate = DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Unspecified);

Since it looks like you are interested in dates starting a midnight, skip the slower string manipulation and instead use the DateTime.Date property.  See help at this link.  Example:

TimeSpan expirationDate = expDate.Date - todayDate;

Which gets rid of all the slower and unneeded string variables, both dates above have the same Kind, and both are set to midnight.


Hackerrank challenge - Dictionaries and Maps

You got it (mostly) right, I'd say. I wouldn't worry about runtime on hackerrank. They're not going to throw massive resources at every piece of code someone uploads. You're basically sharing their server with everyone else, so they're throttling things. Plus, there's just basic network lag.

Still, there's a bug:

N is the number of phonebook entries to read, but after that you should read to the end of input. But your code just reads N times in both cases.

Other things:

The Ruby convention is 2 spaces of indentation. Not 4 spaces, not tabs.
Don't use print and then puts with an empty line; just use puts.
Don't use strip unless you want exactly what it does. Most often, you'll see gets.chomp for input handling. #chomp only strips the trailing linebreak, but leaves other whitespace intact.

And you can shorten the if..else to a ternary:

N = gets.chomp.to_i # make this a constant, because why not
phonebook = {}      # shorter way to write Hash.new

N.times do
  name = gets.chomp
  number = gets.chomp
  phonebook[name] = number
end

until STDIN.eof? do # read to end-of-file (i.e. end of input)
  name = gets.chomp
  number = phonebook[name]
  puts number ? "#{name}=#{number}" : "Not found"
end

However, you could also do something else:

N = gets.chomp.to_i
phonebook = Hash.new { "Not found" } # set a default value for undefined keys

N.times do
  name = gets.chomp
  number = gets.chomp
  phonebook[name] = "#{name}=#{number}" # set the entire output string
end

# Will print the name=number string or "Not found"
puts phonebook[gets.chomp] until STDIN.eof?


Optimizing display of various famous quotes

It seems to me like quotes, creators and margins all belong to the same object; your intuition is correct, merging them into one is the right thing to do.

I don't do much web development, so I'm not going to post example code, but I would have the quotes on the server side, and have the script request them through AJAX.

The server-side would probably define an object such as this:

public class QuoteViewModel
{
    public string QuoteText { get; set; }
    public string Author { get; set; }
    public int Margin { get; set; }
}

The data could come from a database, a web service, an xml file on the server, whatever. When the jquery client requests a quote, the server side serializes a QuoteViewModel into a json string and sends it to the client.

This way all you need to change when you want to modify the quotes displayed, is the data itself.

I don't think Margin belongs on that type though. I'm pretty sure there's a way to use css so that you can only request the QuoteText and Author from the server (in a Json string), and achieve the same result.

Consequently, the first thing I'd do would be to delete the margins array and see what needs to change in order to do without; I warmly recommend you to include the html & css into your question, I'm sure there's something wrong with your markup for you to think you need to recentrize .content depending on what quote is picked.


PHP - Deliberate loose == check and assigning to if statement

Quite so. Except for the trailing comment getting beyond edge. But it can be written in much simpler way anyway.

$medical = $v->getMedical();
$visitorHasMedical = ($medical && $medical->getMedCon());


1-dimensional and 2-dimensional Peak Finding Algorithm

Just reviewing peak1d.

It's not clear from the docstring what kind of object array is. If it might be a list, then the complexity is actually \$O(n)\$, because slicing a list makes a copy.

The copy in array[:mid] or array[mid:] can be avoided by maintaining search bounds instead:

def peak1d(array):
    """Return a peak in array."""
    def peak(start, stop):
        mid = (start + stop) // 2
        if mid > 0 and array[mid] < array[mid-1]:
            return peak(start, mid)
        elif mid < len(array) - 1 and array[mid] < array[mid+1]:
            return peak(mid, stop)
        else:
            return array[mid]
    return peak(0, len(array))

Python doesn't do tail recursion elimination, so the function would be a bit faster if you eliminated the recursion:

def peak1d(array):
    """Return a peak in array."""
    start, stop = 0, len(array)
    while True:
        mid = (start + stop) // 2
        if mid > 0 and array[mid] < array[mid-1]:
            stop = mid
        elif mid < len(array) - 1 and array[mid] < array[mid+1]:
            start = mid
        else:
            return array[mid]


Sort a binary file without loading it into memory or using a temporary file

Don't Repeat Yourself (DRY)

            fseek(dat, i*sajz, SEEK_SET);
            fread(&tx, sajz, 1, dat);
            rewind(dat);

You do this three times.  The general rule is first time write, second time copy, third time refactor into a common function.  Note that if there is sufficient commonality, you may create the common function with only two uses (e.g. with the fwrite version).  Make a function:

void read_at_position(FILE *source, size_t position, size_t size, void *datum)
{
    fseek(source, position * size, SEEK_SET);
    fread(datum, size, 1, source);
    rewind(source);
}

I made datum a void * because that's what fread takes.  This way you don't have to write a new function if you change the datum type.

Now you can rewrite the original section (and the other four) like

            read_at_position(dat, i, sajz, &tx);

If you're worried about the overhead, you could create a macro instead

#define READ_AT_POSITION(source, position, size, datum) \
    do {\
        fseek(source, (position) * (size), SEEK_SET);\
        fread(datum, size, 1, source);\
        rewind(source);\
    } while (0)

which you'd use as

            READ_AT_POSITION(dat, i, sajz, &tx);

And the compiler will turn it into your original version.

Note that a good compiler will probably do that with the function as well.

Better names

The only way that I know what sajz and dat do is from looking at their declarations.  Good names should balance being easy to write (e.g. size) with being descriptive (size_of_each_datum or size_of_float).  Perhaps datum_size instead of sajz.

Similar problem with tjmh and tx.  Neither name tells me anything about what they do.

Consider changing h to gap_size.  Yes, h is a standard name in a shellsort (as per Wikipedia), but will most people remember that if they see it?

Reusability

Rather than writing this directly into main consider making a function.  E.g.

void sort_floats_in_file(FILE *source, size_t datum_size);

You could generalize this by passing in a comparison function.

void sort_in_file(FILE *source, size_t datum_size, int (*compar)(const void *, const void*));

However, that can add unnecessary overhead in simple cases like this.  Perhaps the compiler takes care of that.  Perhaps not.

Robustness

You say

    size_t sajz = sizeof(float); // for convenience

And later

    float tjmh, tx;

Consider flipping the order around and saying

    float tjmh, tx;
    size_t sajz = sizeof tjmh; // for convenience

Then if you change the data type of tjmh and tx, sajz will change to match automatically.  As is, it would be easy to forget and only change in the one place.

Similarly,

    float a;
    if (dat)
    {
        a = 2.00;
        fwrite(&a, sizeof(float), 1, dat);

Consider rewriting this as

    if (dat)
    {
        test_write(2.00, dat);

with

void test_write(float a, FILE *dat)
{
    fwrite(&a, sizeof a, 1, dat);
}

Not only is this less typing, it avoids the problem of changing the type in one place and not the other.  Admittedly there's some extra work to write the function, but the reduction per test case should cover it.


Solving for the zero of an arbitrary function

Wall of declarations

double lowerBound = min,
    upperBound = max;
counter = 0;
double range = double.MaxValue;
double tryIndex = double.MinValue;
double tryEval = double.MinValue;

Nobody likes being greeted by a wall of declarations like that.  Let's see what can be done to reduce them.

lowerBound and upperBound merely rename the parameters.  You could just use min and max directly everywhere.

counter is strongly related to the loop.  You could write the loop as

for (counter = 0; Math.Abs(tryEval) > eps && counter < 10000; counter++)
{
    …
}

range is also local to the loop, and should be declared inside the loop.  It's also annoying that it's initialized on the 4th line of the function, redefined on the 9th line, and used 17th line. In fact, I wouldn't bother making a variable for it at all:

tryIndex = lowerBound + (min - max) / 2;

In general, you have a lot of expressions that don't need to be assigned to variables.

Loop structure

Initializing tryIndex and tryEval to double.MinValue is a code smell.  First of all, you should probably prefer double.NaN.  Secondly, it raises the question, under what circumstances might double.MinValue "leak" out as a result?  It's worth restructuring the program to avoid having those special values at all.

Restructuring the program will also reveal that there are two possible error conditions: failure to converge because the two endpoints evaluate to the same sign, and failure to converge because it took too many iterations.

public static double Zero(this Func<double, double> function, double min, double max, out int counter, double eps = .001)
{
    for (counter = 0; counter < 10000; counter++)
    {
        bool signMax = (function(max) > 0);
        if ((function(min) > 0) == signMax)
        {
            // Same sign
            throw new Exception("Failed to converge (same sign)");
        }

        double tryIndex = min + (max - min) / 2;
        double tryEval = function(tryIndex);
        if (Math.Abs(tryEval) <= eps)
        {
            return tryIndex;
        }
        else if ((tryEval > 0) == signMax)
        {
            max = tryIndex;
        }
        else
        {
            min = tryIndex;
        }
    }
    throw new Exception("Failed to converge (too many iterations)");
}


Function prefix qualifiers
I seem to remember this being covered in your reviews before, but:
const inline size_t find(const size_t x)

This benefits from neither of the const declarations nor the inline. Both the return value and the argument are passed-by-value scalars and do not benefit from const. inline, for all intents and purposes, has no effect, particularly where a compiler is told to optimize your code - and even if it did have an effect, it's a bad idea to tell the optimizer what it should and shouldn't inline. It will understand what's good for your code better than the programmer does 99% of the time.
If these concepts are confusing or difficult to apply to code on a practical basis, that is understandable - feel free to ask follow-up questions.


A server response written in node/express/mongodb: does this look right?

Here are some simple tips.

1)

You can combine the two if conditions for if(docs) and if(errors.length != 0), since if docs is true, then errors has positive length.

Old Code:

if (docs) {
    errors.push({
        'field' : field,
        'message' : errorMessage
    });
}
if (errors.length) {
    errors.push({
        field : "workspace",
        message : "Workspace taken, sorry!"
    });
    serverResponse(res, errors);
    return;
}

New Code:

if (docs) {
    errors.push({
        field : "workspace",
        message : "Workspace taken, sorry!"
    });
    serverResponse(res, errors);
    return;
}

2)

For this sitation, it's best not to make multiple function calls to the same function.

Old Code:

var serverResponse = function(res, errors){
  if(errors.length){
    res.json( { response: 'ERRORS', errors: errors } , 200)
    console.log("Sent ERROR");
  } else {
    res.json( { response: 'OK' } , 200)
    console.log("Sent OK");
  }
}

New Code:

var serverResponse = function (res, errors) {
    var status = {};
    if (errors.length) {
        status.response = 'ERRORS';
        status.errors  = errors;
    } else {
        status.response = 'OK';
    }
    res.json( status, 200 );
    console.log( "SENT " + status.response );
}

3)

Pass warnings but not errors. Deal with errors immediately.

4)

Avoid having too many else conditions. Use a if guard to avoid this.

Old Code:

function a( err ){
    if( err ){
        throw new Error( err );
    }else{
        //... code
    }
}

New Code:

function a( err ){
    if( err ){
        throw new Error( err );
        return
    }
    //... code
}

*/

5)

Don't repeat yourself.

6)

Split up functions longer than 8 - 12 lines into smaller functions.

7)

if(errors.length != 0){ is the same as if(error.length){.

8)

Try to only have 1 nexted functions created in a single function. The setTimeout section has this problem.

9)

If it doesn't hurt the performance or security of the program then I would make User and Workspace global variables. Otherwise you could pass them where needed.

Final Code Revision

var User, Workspace;
var serverResponse = function (res, errors) {
    var status = {};
    if (errors.length) {
        status.response = 'ERRORS';
        status.errors  = errors;
    } else {
        status.response = 'OK';
    }
    res.json( status, 200 );
    console.log( "SENT " + status.response );
};
var getDatabaseRequestFunc = function (field, errorMessage, callback) {
    return function (err, docs) {
        if (err) {
            next("Database error fetching field: " + field);
            return;
        }
        if (docs) {
            var error = [{
                'field' : field,
                'message' : errorMessage
            }];
            serverResponse(res, error);
            return;
        }
        callback();
    };
};
var getUserSaveFunc = function (req, res, next, user) {
    return function (err) {
        if (err) {
            next("Database error saving user");
            return;
        }
        var w = new Workspace();
        w.name = req.body.workspace;
        w.activeFlag = true;
        w.ownerUserId = user._id;
        w.countryId = null;
        w.save(function (err) {
            if (err) {
                next("Database error saving workspace. WATCH OUT: user " + user.login + " doesn't have a workspace!");
                return;
            }
            serverResponse(res, []);
        });
    };
};
var registerWorkspace = function (req, res, next) {
    Workspace.findOne({
        name : req.body.workspace
    }, getDatabaseRequestFunc( "workspace", "Workspace taken, sorry!" , function(){
            var u = new User();
            u.login = req.body.login;
            u.password = req.body.password[0];
            u.workspaceIds = [];
            u.save(getUserSaveFunc(req, res, next, u));
        })
    );
};
var registerUserLogin = function (req, res, next) {
    User.findOne({
        login : req.body.login
    }, getDatabaseRequestFunc( "login", "Login name taken, sorry!" , function(){
            registerWorkspace(req, res, next);
        })
    );
};
exports.nonApiRegister = function (req, res, next) {
    setTimeout(function () {
        User = mongoose.model("User");
        Workspace = mongoose.model("Workspace");
        registerUserLogin(req, res, next);
    }, 500);
};


ConcurrentDictionary, Store Key and Compression

GetHashCode is used internally by ConcurrentDictionary to speed up access to the real key.

But, there is no guarantee that 2 different strings will return 2 different HashCode, you may encounter collisions! Such collisions are handled by the ConcurrentDictionary.

So with your code, as the _compilerCache is a Dictionary<int,functor> (it seems to be) and not a Dictionary<string,functor>, you may encounter rare events where two different codes will give the same key. If such a collision happends, you have a subtle and rare bug.

I suggest the following :

stick to a Dictionary<string,functor>, use the real key
don't input a HashCode instead of the real key
you may also input your own GetHashCode in Dictionary constructor

Using code instead of int as a key has a price : memory footprint is larger, but with small strings (10-20 char), it should not be an issue.

Hope this helps !


UnitOfWork, removing abstraction of abstraction (Repository)

I realize you said

  my naming/style is inspired by them.

But I would still point out some of your naming conventions which don't align with C#s.

Method/Function level variables should be camelCase instead of PascalCase

public string GetUserName(string Name)
public string GetUserName(string name)

Same as before, and as a note _underscores should only be used for class level variables.

public UserService(IUnitOfWork _u)
public UserService(IUnitOfWork u)

Not required, but a common practice is also that you do indeed use underscores for class level variables

private readonly IUnitOfWork unitOfWork;
private readonly IUnitOfWork _unitOfWork;

Make sure you are disposing(closing) your database object. I presume by the way you have your class setup that when your database object is disposed it will close, in which case I would recommend using the using keyword. Which would make your above code look more like this in practice.

using(var database = Database.Open())
{
    var userName = database.Users.GetUserName("John");
    var userFirstName = database.Users.GetFirstName("john123");
}

This ensures that you are always closing your connection in the end.

Be careful when debugging your code, and remember (depending on your db setup) if you pause the debug in your code while the connection is open, you wont be able to use the database. Also if you have any plans to do mulithreading with this you'll want to use locks.


Yaw (Z-rotation) angle linear interpolation without quaternions

Finding shortest angular distance.
I have always found the method of normalising angles with
const PI2 = Math.PI * 2;
var angle = ((angle % PI2) + PI2) % PI2;

and then finding the shortest angular distance a little bit hacky. This is even more so when the angles are originally vectors.
Cross and dot products.
Math.asin of the cross product of two vectors gives the angle left or right of first vector in the range -90 to 90 deg and the sign of the dot product will indicate if the vectors are in the same direction or not letting you get the quadrant the second vector is in and thus the shortest angular direction from one vector to the next.
The results are always relative to the direction of the first vector so you dont need to normalise the angle to 0 -Math.PI * 2
Polar to cartesian
As you want to work in angles (polar) you just need the extra step of calculating the cartesian vectors.
The function to find the shortest angular distance between any two bearings (angles).
// a and b are angles in radians
// returns direction in radians
function shortestAngle(a,b){
    const ax = Math.cos(a); // create vector a
    const ay = Math.sin(a);
    const bx = Math.cos(b); // create vector b
    const by = Math.sin(b);

    // asin cross product to find angle
    const angle = Math.asin(ax * by - ay * bx);

    // and dot to help find the quadrant
    const dot = (ax * bx + ay * by);

    // if facing in different direction dot < 0 angle will be
    // over 90 or under -90 else between  90 and -90
    return dot < 0 ? Math.sign(angle) * Math.PI - angle : angle;
}

Then to interpolate you just scale the result of the above function
// a is start angle
// angDist is angular distance
// time is time in range 0 to 1
function slerp(a, angDist, time) {
    return angDist * time + a;
}

Gives in my view, a cleaner less hacky solution.
 // using
 var angle1 = ?
 var angle2 = ?
 var angDist = shortestAngle(angle1, angle2);
 var angle = slerp(angle1, angDist, time);

Which is even better if you are already working with vectors rather than angles.


Shortest distance between two words in the list

Care about final

Your parameters are never modified, so it is good practice to mark them final. Probably the method too, unless you expect it can be overridden.

public final int shortestDistance(final String[] words, final String word1, final String word2)

Compare by indices

Instead of your for loop, you can use the indices of the elements.

public final int shortestDistance(final String[] words, final String word1, final String word2) {
   final List<String> wordsList = Arrays.asList(words);

  final int word1Index = wordsList.indexOf(word1);
  final int word2Index = wordsList.indexOf(word2);

  return Math.abs(word2Index - word1Index);
}

There could be duplicates

We can solve this problem by finding the index of each occurrence. The final product:

public final int shortestDistance(final String[] words, final String word1, final String word2) {
  final List<Integer> word1Indices = IntStream.range(0, words.length).boxed().filter(i -> words[i].equals(word1)).toList();
  final List<Integer> word2Indices = IntStream.range(0, words.length).boxed().filter(i -> words[i].equals(word2)).toList();

  int result = Integer.MAX_VALUE;

  // Better way to do this but I'm tired.
  for(final Integer word1Index : word1Indices) {
    for(final Integer word2Index : word2Indices) result = Math.min(result, Math.abs(word2Index - word1Index));
  }

  return result;
}


Money class for handling calculations with coins

There is a general purpose guideline - the Single Responsibility Principle. For a given procedure/function you should be able to write a simple statement "This code does X." If you find yourself writing "This code does X and Y." then you should consider breaking the code up into pieces - one piece that does X and one piece that does Y.

The code above does three things - reads input, calculates change, writes output. Those three pieces are candidates for creating separate functions.

I say candidates because there is always a trade-off. When you extract some code into a new function/method then you also have to be able to communicate input to the new function/method as well as for it to communicate back its results. Your code is fairly simple and straightforward as is. Even though it has three different parts and is longer than would be preferred for a single function, splitting it up wouldn't improve it that much while at the same time adding extra complication/overhead in the method calls and returns.

However, that said, if this code became the basis for a more advanced assignment, one thing that you could do would be to create a Change or Payment class something like I have shown below. It encapsulates two parts of the functionality in your code in a simple and direct way that provides a basis for adding additional features.

For example, if you needed to calculate the amount tendered from counts of coins and bills, you could add a function that reads a count of coins tendered and another that calculates the total value.

class Payment {
    int dollars = 0;
    int quarters = 0;
    int dimes = 0;
    int nickels = 0;
    int pennies = 0;

    public payment(int value) {
        int remainder = value;

        dollars = remainder / 100;
        remainder = remainder % 100;

        quarters = remainder / 25;
        remainder = remainder % 25;

        dimes = remainder / 10;
        remainder = remainder % 10;

        nickels = remainder / 5;
        remainder = remainder % 5;

        pennies = remainder;
    }

    public writeOutput(PrintStream out) {
        out.println("\t \t " + dollars + " one-dollar bills(s)\n \t \t "
                             + quarters + " quarter(s)\n \t \t " + dimes +
                             " dime(s)\n \t \t " + nickels + " nickle(s)\n \t \t " +
                             pennies + " penn(y/ies)");

    }
}


Just a few things

To start out, the return statement in your function completeCustomers should/could be changed.

The way the function is defined should also be changed. But we'll get to that in a second.

return (updatedCustomers = customers.map((customer, index) => {
  const updatedCustomer = Object.assign(customer, addresses[index]);

  return updatedCustomer;
}));

I would replace with:

return (updatedCustomers = customers.map((customer, index) => ({
  ...customer,
  ...addresses[index]
})))

Note, you don't have to make it take up multiple lines if you don't want.

Use const when you don't modify a variable, or arrow function

This means that the two functions below need to change:

completeCustomers = (filePathCustomers, filePathAddresses) => {

Would become:

const completeCustomers = (filePathCustomers, filePathAddresses) => {

let execCompleteCustomer = new Promise(resolve => {

And this would become:

const execCompleteCustomer = new Promise(resolve => {

That's all I have for now, but I'm not getting what part you are saying is redundant. And I think you handled the errors well.


Your function is called generate but it doesn't return anything. Instead display would be a better name.
It would be better if you had two functions one to generate the values, one to display them.
Function names should be lower_snake_case to be idiomatic.
+ " " is not needed, as print makes the value go to the next line anyway.
str(number) also isn't needed as print will do this automatically for you.

Thanks @Toby Speight:

You can move the print to be after both the if and the else.

def generate_collatz_sequence(number):
    output = [number]
    while number != 1:
        if number % 2 == 0:
            number = number / 2
        elif number % 2 == 1:
            number = (3 * number) + 1
        output.append(number)

def display_collatz_sequence(values):
    for number in values:
        print(number)

If you want this to still display values in real time, then you can make generate_collatz_sequence a generator function.

def generate_collatz_sequence(number):
    yield number
    while number != 1:
        if number % 2 == 0:
            number = number / 2
        elif number % 2 == 1:
            number = (3 * number) + 1
        yield number


Next node of a node in Binary search tree

1

NodeWithParent does not sound funky to me: why not try TreeNode.

2

You can drastically simplify (and rename) the nextNode method:

public static final TreeNode getSuccessorNode(TreeNode node) {
    if (node == null) {
        return null;
    }

    if (node.right != null) {
        return getMinimumNode(node.right);
    }

    TreeNode parent = node.parent;

    while (parent != null && parent.right == node) {
        node = parent;
        parent = parent.parent;
    }

    return parent;
}

3

Also, it is conventional to start a class name with a capital letter (NextNodeOfANodeInBST). Actually, a better name for you class may be something as BSTUtils or, say, BinarySearchTreeUtils.

4

In your main you have root.parent = null; You don't have to: by default all reference fields in a class are initialized with null.

5

In case your class contains only static methods, it's customary to declare the constructor of such a class as private: it makes no sense to instantiate an object that does nothing in its own right.

Hope that helps.


As @user1118321 points out: just using your implementation, I believe you're missing a crucial line (inside your for loop and if-statement):

longestCount = element.length();

Which becomes:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;

string LongestWord(string sen) {
    vector<string> coll; //initialize vector

    istringstream iss(sen); //read the string "sen"

    copy(istream_iterator<string>(iss), //copy from beginning of iss
        istream_iterator<string>(), //to the end of iss
        back_inserter(coll)); //and insert string to vector
    //istream_iterator by default separates word by whitespace

    string longestWord = coll.at(0);
    int longestCount = longestWord.length();

    for(auto element : coll)
    {
        if(element.length() > longestCount)
        {
            longestWord = element;
            longestCount = element.length();
        }
    }

    return longestWord;
}

Don't use using namespace std, it's better to use std:: as needed. While it's insignificant here, if you work on larger projects it will cause headaches. Especially if you're learning STL, it's a good idea to learn what goes in the STL and the C++ Standard Library (ie within namespace std).

Instead of iterating over the string (when tokenizing into words) and again over the vector, you could just iterate once:

Below is a common way to find the maximum of a container of elements, in this case std::vector<std::string>, while taking advantage of std::istringstream:

#include <sstream>
#include <string>

std::string LongestWord(std::string str){
    std::string::size_type max_len = 0;
    std::string longest_word;
    std::string word;

    std::istringstream stream(str);

    while(stream >> word) {
        if(max_len < word.length()) {
            max_len = word.length();
            longest_word = word;
        }
    }

    return longest_word;
}

This function could be improved depending on how you wish to use it. You may wish to not count punctuation (recommended), you may wish to return a vector of strings if there are words of the same length, or you may wish to throw an error when given an empty string. These are all fairly easy to implement as needed.


Saving away URL query parameters in an analytics application

Your server sets up a cluster, then listens for requests. It parses a parameter from the request URL, and writes it to file.

For performance reasons, that write to file should be asyncrhonous. Currently your client has to wait for your log to write before the client continues.... but, here's the real flaw in your code....

... you do not send a response at all to the client!

You need to actually process the response by sending a status code, and ending the communication:

 response.writeHeader(200); // success
 response.end();

Client sessions will just sit there hanging until you do that.


The id attribute must to be unique per document. So I think that using ID for the cover image is wrong under the assumption that you may have many pills per page with covers.

I believe that using a class cover would be better in this case. You can still use .pill > .cover selector in the same way to only select covers under pills.


My first issue is that this function is badly named.

    void is_cousins(TreeNode* root, int to_find, int depth,
        TreeNode* parent, pair<int, TreeNode*>& pair)

It has nothing to do with cousins. It is simply finding the depth and parent of a particular value. You should name it appropriateely.

I don't like passing output parameters to a function:

    void is_cousins(TreeNode* root, int to_find, int depth,
        TreeNode* parent, pair<int, TreeNode*>& pair)

The parameter pair is the output of the function. Why not just return this value. That would be more logical and easier to read.

You don't have a truth state on whether the value x or y are found. I suppose you could say that nullptr in pair is a good way to test this. But that will make things complicated down the road when you try and use this function for other things that are not cousin related; so I don't like that idea. You could used a depth of -1 to indicate failure that would be better.

Talking of default values:

Your current default result is make_pair(0, nullptr) this means you found the root as the value (even if the root value does not equal left of right). This may work for your current situation out of sheer luck but you are returning a bad value.

i.e. A value that is not found in the tree and the root node will both return the same result.

Here is a major ineffeciency.

    is_cousins(root->left, to_find, depth + 1, root, pair);
    is_cousins(root->right, to_find, depth + 1, root, pair);

If you find the value on the left you still search the right subtree. This means you always search the whole tree even if you find the correct node very quickly.

You should check the result of the left search before doing the right search.

This is an anti patten

        if (pairx.first == pairy.first && pairx.second != pairy.second)
            return true;
        return false;

The pattern:

        if (test) {
            return true;
        }
        return false;

        // Can always be simplified to:

        return test;

This is a long handed way of writing:

         return pairx.first == pairy.first && pairx.second != pairy.second;

If you think that is too long for an expression to use in a reurn, then it is too long an expression for any context. In that case you should put the test in a named function so it is obvious what it is doing.

          return are_cousing_nodes_from_Depth(pairx, pairy);

     using DepthInfo = pair<int, TreeNode*>;
     inline bool are_cousing_nodes_from_Depth(DepthInfo const& lhs, DepthInfo const& rhs)
     {
         return lhs.first  == rhs.first    // Same depth
             && lhs.second != rhs.second;  // Not siblings
     }


// making setter private so it will be impossible to modify account from
// outside
private void setCurrentAccount(int currentAccount) {
    this.currentAccount = currentAccount;
}

So, what's the point of this setter at all? :)


For the most part, that's nice code. I can read it somewhat easily, and for the most part, it is logical, and structured.
There are a number of issues in your code, though, some style issues, and some functional issues.
First up, the style issues.
Using the existing libraries
There's a nice feature in ThreadLocal in Java8 that allows you to have a supplier for the structure. Consider a method like:
private static RandomGenerator buildGenerator() {
    .....
}

then your thread local can be created as:
private static ThreadLocal<RandomGenerator> instances =
       ThreadLocal.withInitial(ThreadLocalRandomGenerator::buildGenerator);

Your main method can become a simple:
public static RandomGenerator get() {
    return instances.get();
}

It is guaranteed that there will be an instance created for you on the first call from a thread.
Getting good seeding
Your seeding system is both complicated, and wrong.
If you are looking to have a special random generator that you feel out-performs the existing Java Random class, that's OK, but, it needs to be seeded right.
There are a few problems in your seeding that I can see. First up:

seed[0] = (int) (System.currentTimeMillis() & 0xffffffffL);

That can be simply an int cast. No need to mask off the bits:
seed[0] = (int)System.currentTimeMillis();

Next up, is that computers have different precision in their nano clocks. A nano-second is far faster than the actual computer's time interrupt, so, it is common for computers to "step" significantly as it updates. The steps can be as much as 190 nanoseconds is where i have seen it....
... what that means, is that the results for all your seed values here may be the same:

seed[i] |= (int) ((System.nanoTime() & 1L) << j);

In other words, you will have int values filled with either 0's or 1's... and no variations. Also, if the "step" for the nano-second clock happens to be an even number, it is possible that the low-order bit for your computer will always be the same value.... and all your seeds will be identical.
While the Random class in Java may be slower than you want, you can at least use it to seed the faster ISAAC algorithm.
I would simply use the following to seed your class:
Random rand = new Random();
int seed[] = rand.ints(256).toArray();

Use the slower Random to seed your class, then let your class run with the rest.
Note, there is no real way to use the time systems in a computer to get random values... it's just not infused with enough entropy to be random, or predictability to be reliable.


"Actually you code is pretty much this. Simple and boring as most other good Go code" I thought.
At this point I could say "Wrap your c <- true with a select statement, add the third case <-ctx.Done: to handle possible deadlock and you are ready to go".
But.
Does it really should be this way? Yep, this works and does the job, but are there any pitfalls we missed? Let see.
Indentation
Let's talk about idiomatic Go. Within the space of idiomatic Go a proper indentation is a single Tab rendered as 8 spaces:
func intersectChans(a <-chan bool, b <-chan bool) {
        for {
                select {
                case <-a:
                        select {
                        case <-b:
                                select {
                                case c <- true:
                                case <-ctx.Done():
                                        return
                                }
                        case <-ctx.Done():
                                return
                        }
                case <-ctx.Done():
                        return
                }
        }
}

Okay, the first pitfall we have is a deep code indentation.
Well, not really a problem because, khm, Idiomatic Go, it is you, who decided to render 8 spaces for a single Tab in the first place. And the Linux kernel C style guide as well.
Actually there is a good reason for this. Let me quote the style guide I linked above:

Now, some people will claim that having 8-character indentations makes the code move too far to the right, and makes it hard to read on a 80-character terminal screen. The answer to that is that if you need more than 3 levels of indentation, you’re screwed anyway, and should fix your program.

OK, we definitely have "too far to the right" movement here. Let's consider this a pitfall, but not a critical one.
Channels
This code is all about the channels. We have 4 here:

a and b channels to receive data
c channel to send aggregated results from a and b
ctx.Done() channel to terminate the goroutine

What can we do with channels? We can:

receive
send
and close the channel

ctx.Done() channel is closed to tell goroutine that the task is done. But what about our own channels?

You needn't close every channel when you've finished with it. It's only necessary to close a channel when it is important to tell the receiving goroutines that all data have been sent. A channel that the garbage collector determines to be unreachable will have its resources reclaimed whether or not it is closed.

says some book about Go.
OK, so we can close a channel to notify its reader, that all data has been sent.
But a read from a closed channel still returns some data. It will be a zero value of the channel data type. To actually check, that the channel was closed, we can use the "comma ok" idiom:
data, ok := <- a
if !ok {
        fmt.Println("a was closed")
}

OK, but why will we do it in the first place?
A not so boring solution
If we combine our strive to have a more flat code with an ability to check for closed channels we can come up with a solution like this:
func join(a, b <-chan int, r chan<- []int) {
        defer close(r)
        for {
                v1, ok1 := <-a
                v2, ok2 := <-b
                if !(ok1 && ok2) {
                        return
                }

                r <- []int{v1, v2}
        }
}

In this code sample we are using "comma ok" idiom to test for a closed worker channels and stop processing.
This code relies on the fact, that worker goroutines will close their channels to notify us, that all data has been sent. We do the same and close our channel with a defer statement.
And here are the missing parts (also on Go Playground):
package main

import (
        "context"
        "fmt"
        "time"
)

func worker(ctx context.Context, c chan<- int) {
        defer close(c)
        for i := 0; ; i++ {
                select {
                case <-ctx.Done():
                        return
                case c <- i:
                }
                time.Sleep(time.Second / 4)
        }
}

func join(a, b <-chan int, r chan<- []int) {
        defer close(r)
        for {
                v1, ok1 := <-a
                v2, ok2 := <-b
                if !(ok1 && ok2) {
                        return
                }

                r <- []int{v1, v2}
        }
}

func main() {
        ctx, cancel := context.WithTimeout(context.Background(), time.Second)
        defer cancel()

        a := make(chan int)
        b := make(chan int)
        r := make(chan []int)

        go worker(ctx, a)
        go worker(ctx, b)
        go join(a, b, r)

        for pair := range r {
                fmt.Printf("got %+v\n", pair)
        }
}

"So, which solution should I take?" will you ask.
It depends. One solution is a simple and boring Go code. The other is "not that far to the right", but has some fancy channel operations not everybody even know exists.
And while you decide, don't forget to fix a possible deadlock in your actual code :)


Class library for processing credit cards

First, I hope this question is still relevant in your company. One point that is of great interest to me in the question, is the management's vision to use other 3rd party payment processing providers. This directly implies that the code should accomodate this by abstracting the operation of processing orders and resolving dependecies on external systems.

I will give some simple suggestions intended to decouple the code from a specific implementation (therefore enhancing code re-use and testability)

Step I, Resolve dependency on 3rd party credit services

This is acheived by abstracting the functionalities exposed by the service (of course every service will have a different API, but the processing logic will follow more or less the same workflow):

public interface IPaymentGateWayService
{
    List<X509Certificate> ClientCertificates { get; }
    string Url { set; }
    NetworkCredential Credential { set; }
}

So now your Payment processor is agnostic to which service it is using as such:

class PaymentProessor
{
    private readonly IPaymentGateWayService _paymentGateWayService;

    public PaymentProessor(IPaymentGateWayService paymentGateWayService)
    {
        _paymentGateWayService = paymentGateWayService;
        _propertyProvider = propertyProvider;
    }

    public void ProcessCreditCardPayment()
    {
        _paymentGateWayService.Url = /*service url*/;
        _paymentGateWayService.ClientCertificates.Add(/*X509 certificate*/)
        _paymentGateWayService.Credential = new NetworkCredential(/*username and password*/);

    }
}

You then create a wrapper for your FDGGWApiOrderService that implements the IPaymentGateEayService interface:

class FDGGWS : IPaymentGateWayService
{
    private FDGGWSApiOrderService _fdggwsApiOrderService;

    public FDGGWS()
    {
        _fdggwsApiOrderService = new FDGGWSApiOrderService();
    }

    public List<X509Certificate> ClientCertificates
    {
        /*delegate to _fdggwsApiOrderService*/
    }

    public string Url
    {
        /*delegate to _fdggwsApiOrderService*/
    }

    public NetworkCredential Credential
    {
        /*delegate to _fdggwsApiOrderService*/
    }
}

So now when you create your payment processor, you pass the instance of the service you want to use.

new PaymentProessor(new FDGGWS());

This simply allows you to reuse your code to accomodate different service providers, also, you can support multiple providers at the same time by creating a service factory that returns the desired concrete instance of teh service depending on a configuration setting.

Step II, Handle environment settings

There are tons of techniques that allow you to read values from configuration stores, like App.config or a web.config. But for the purpose of my answer I will leverage the dependency injection technique and resolve the dependency on environment properties using constructor injection, similar to what is used to abstract the service interface.

So we create an interface for the configuration settings:

internal interface IPropertyProvider
{
    string Cert_File { get; }
    string Cer_User { get; }
    string Cer_Password { get; }
    string ServiceUrl { get; }
}

And you can create as many flavours of the interface as there are environments, in your case of for test and one for production, here is an abridged example of either:

class ProductionPropertyProvider : IPropertyProvider
{
    public string Cert_File
    {
        get { return "Path to Production file"; }
    }

    /* other properties */
}

class TestPropertyProvider : IPropertyProvider
{
    public string Cert_File
    {
        get { return "Path to test file"; }
    }

    /* other properties */
}

And here is how you perform the dependency injection:

class PaymentProessor
{
    private readonly IPaymentGateWayService _paymentGateWayService;
    private readonly IPropertyProvider _propertyProvider;

    public PaymentProessor()
        :this(new FDGGWS(), new ProductionPropertyProvider())
    {}
    public PaymentProessor(IPaymentGateWayService paymentGateWayService, IPropertyProvider propertyProvider)
    {
        _paymentGateWayService = paymentGateWayService;
        _propertyProvider = propertyProvider;
    }

    public void ProcessCreditCardPayment()
    {
        _paymentGateWayService.Url = _propertyProvider.ServiceUrl;
        _paymentGateWayService.ClientCertificates.Add(X509Certificate.CreateFromCertFile(_propertyProvider.Cert_File));
        _paymentGateWayService.Credential = new NetworkCredential(_propertyProvider.Cer_User, _propertyProvider.Cer_Password);

    }
}

Notice the default constructor that creates default service and property provider instances. This is just to demonstrate that you can specify the default dependencies in the default constructor

Lastly, all you need is one configuration key in your app.config that specifies what environment is it.. we use that key to determine the type of the IPropertyProvider.

Example

//Read env setting from the application configuration file
var environment = ConfigurationManager.AppSettings["env"];

//create appropriate PropertyProvider
IPropertyProvider propertyProvider;
if (environment == "test")
    propertyProvider = new TestPropertyProvider();
else
    propertyProvider = new ProductionPropertyProvider();

//process the payment
new PaymentProessor(new FDGGWS(), propertyProvider).ProcessCreditCardPayment();


Objects/closures for storing movie information

You're using the "module" pattern, which works well for many use cases. Your code for this pattern is correct as it stands. The best pattern to use is more about how you are planning to use it.

Some different patterns and why they might be better depending on your use case:

This module pattern is a little difficult if you ever needed to create two movie lists on the same page. A different pattern would be the constructor pattern. This would allow you to easily initialize a new list on the same page.
One potential issue with this pattern is there is a lot of private variables. While this is sometimes good design, when you want to unit test this code, it might be faster to have these private variables available, so you can manipulate them for the test. You can do this with the revealing module pattern, or the constructor pattern which will expose them.


Correct use of Serializable with lambda functions

I'm  going to answer my own question. Never do this!. I have just tried saving a new Filefilter object with this filter:
.addFilter("Delete files, Delete all files",f->f.delete());

And when selected, it deletes all the files in the current directory.


Code to calculate similarity between strings - R

Here is an implementation of the ideas I had suggested in the comments: to store the output of levenshteinSim so it is only called once, and to limit the expensive name comparisons to individuals that share the same initials. I hope it helps.

names_vec <- data$nomeAlt
initials  <- gsub("\\b(.).*?\\b", "\\1", x)

similar <- list()
for (i in 1:length(names_vec)) {
   ini <- initials == initials[i]
   sim <- levenshteinSim(names_vec[i], names_vec[ini])
   idx <- which(sim > 0.85 & sim != 1)
   similar[[i]] <- if (length(idx) == 0) NA else ini[idx]
   print(i) # to get an update of the progress
}


Performant functional evaluation for enum value

BigDecimal orderPrice = order.getSide().ifAsk(calcAskPrice(order)).ifBid(calcBidPrice(order)).elseFail();

This seems rather long and complicated.  Consider

BigDecimal orderPrice = order.getSide().calculatePrice(order);

Or you might hide it as

BigDecimal orderPrice = order.calculatePrice();

With

BigDecimal calculatePrice() {
    return getSide().calculatePrice(this);
}

As you can read on Stack Overflow, you can then define different implementations of the method for each value of the enum.

public enum Side {

    ASK {
        @Override
        public BigDecimal calculatePrice(Order order) {
            return Something.calcAskPrice(order);
        }
    },
    BID {
        @Override
        public BigDecimal calculatePrice(Order order) {
            return Something.calcBidPrice(order);
        }
    };

    public BigDecimal calculatePrice(Order order) {
        throw new IllegalArgumentException("The provided order must have a side that is either ASK or BID");
    }

}

I wrote Something, as you don't provide enough context to write whatever it actually is.  It's possible that the calcAskPrice and calcBidPrice methods should have their contents pulled into the override methods.  Or that you need to pass some kind of additional object to the calculatePrice methods.

There's an argument that overriding a method like this is bad form.  I'll leave it up to you if that matters.  I did it here to duplicate your original functionality.  But maybe you don't need the original functionality.  Again, without more context, it's difficult to tell.

Perhaps it should go without saying, but I didn't test this, as there isn't enough context.  I did not go the extra mile and verify syntactical correctness by dummying up a driver for this code.


Character Picture Grid exercise - automatetheboringstuff

Your code is pretty good. It's what I'd expect the author of the book to have wanted their readers to write.

Good job!

In terms of making the code more understandable/maintainable you can get the same functionality using zip, *args, ''.join and a single print.

for column in zip(*grid):
    print(''.join(column))


Avoid using in header files
It looks like the code you have written is in a header file, which is to be included in an actual application that needs to intersect polygons. If you include this file, it also means you pull in all the using declarations, which could result in unexpected behavior. It might be safe to move the using declarations into class Polygon, but I'd rather avoid doing it altogether.
You also forgot using std::nullopt.
The move constructor should take a non-const reference
Since you want to  move things from an object, that object might have to be modified, so move constructors should take non-const references.
Consider adding operator&()
Polygon intersection shares a lot of similarities with bitwise AND operations. It makes sense to add an operator&() to your class, so you can write:
Polygon a{...}, b{...};
Polygon c = a & b;

Your sorting function is wrong
You can't sort polygons into counter-clockwise order the way you did. The angles you calculate are relative to coordinate (0, 0), but the polygons themselves can be anywhere. You have to calculate the angles relative to a point inside the intersection.
See this StackOverflow question for a possible algorithm.
Alternatively, since the points of the input polygons are already sorted, and the intersection of two convex polygons is just two pieces of each polygon concatenated, you should not need to sort at all.


Extracting necessary records from LinkedIn

I would recommend a more modular design - having a LinkedInScraper class, initialized with a login and password and with separate methods for logging in and getting profile links.

Also, I think you are overusing the XPaths overall - whenever possible, first explore if you can use "by id", "by name" or "by css selector" locators and fall back to XPath only if you cannot get to the element with other locators.

Also note that wait.until combined with built-in expected conditions returns a WebElement instance - if you are waiting for a specific element and then clicking it - you can do it in one go without re-finding the element.

Unfortunately, cannot test the below code (for some reason, I don't see the recommendation link on the main page when logging in with my credentials), but hope this is still useful:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class LinkedInScraper:
    def __init__(self, username, password):
        self.driver = webdriver.Chrome()
        self.wait = WebDriverWait(self.driver, 10)

        self.login(username, password)

    def __del__(self):
        self.driver.close()

    def login(self, username, password):
        self.driver.get('https://www.linkedin.com/')

        self.driver.find_element_by_id('login-email').send_keys(username)
        self.driver.find_element_by_id('login-password').send_keys(password)
        self.driver.find_element_by_id('login-submit').click()

    def links(self):
        follow_link = self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.feed-s-follows-module__view-all")))
        follow_link.click()

        while True:
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

            self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.feed-s-follow-recommendation-card__profile-link")))

            links = [item.get_attribute("href") for item in self.driver.find_elements_by_css_selector("a.feed-s-follow-recommendation-card__profile-link")]
            if len(links) == 200:
                break

        return links

    def profiles(self):
        for link in self.links():
            yield from self.profile(link)

    def profile(self, profile_link):
        self.driver.get(profile_link)

        for item in self.driver.find_elements_by_xpath("//div[contains(@class,'pv-top-card-section__information') or contains(@class,'org-top-card-module__details') or (@class='org-top-card-module__main-column')]"):
            name = item.find_element_by_xpath(".//h1[@title]|.//h1[contains(@class,'pv-top-card-section__name')]").text
            title = item.find_element_by_xpath(".//span[contains(@class,'company-industries')]|.//h2[contains(@class,'pv-top-card-section__headline')]").text

            yield (name, title)

if __name__ == '__main__':
    scraper = LinkedInScraper(username='username',
                              password='password')
    for profile in scraper.profiles():
        print(profile)

I am pretty sure we can also refactor the profile() method, but I cannot get to that page in order to see if locators can be simplified.


Determining if the movement of a robot is possible in a row

First, you are defining too many variables.  Instead of making a list of tuples and then converting it to a flattened list with a different name, you should make the list out of numbers in the first place.  It would also be better to use a set instead of a list.  Your if statement is a little odd.  not j <= i is the same as j > i, but harder to read.  If j must be greater than i, why does your first check include abs()?  Since j > i is an easier operation than the other check, it should come first.  That way, if it is False, the other check won't even be evaluated and the whole thing is more efficient.  You could also use a comprehension instead of a four-line for loop:

def row_walk(matrix):
    used = set()
    for i, r1 in enumerate(matrix):
        for j, r2 in enumerate(matrix):
            if j > i and r1+r2 == j-i:
                used.update((i, j))
    return [x for x in range(len(matrix)) if x not in used]

If you can use a set instead of a list, you can use a better return statement:

return used.symmetric_difference(range(len(matrix))

This all assumes that you are using Python 3.  If you are using Python 2, use xrange() instead of range().  Although range() still exists in Python 2, it creates a list instead of an iterator.


I am not sure if these are bottlenecks, but they are at least performance improvements.

Replace Stack<Token> with Stack<Value> since you are only pushing/popping Value. This way there is no need to do expensive casts.
You can replace

if ( value[ i ] is Operator )
{
    Operator op = (Operator)value[ i ];

with

Operator op = value[ i ] as Operator;
if ( op != null ) // it was an Operator

to have only one typecheck (x as y) instead of two (x is y and (y) x).
You can replace

for ( int i = 0 ; i < value.Count ; ++i )

with

foreach(Token item in value)

to eliminate the index operations value[ i ].


Code formatting

Format your code to improve readability and hence maintainability.

DRY (Don't Repeat Yourself) Principle

You have a lot of places with duplicate code. You should try to avoid this.

First of all in your core2 method you have calls in all condition blocks, you should move it below to be executed in any case.

Also you have many duplicate code in your calc methods. You can move duplicate code to your core core2 method.

Inconsistent styles

Use the same style everywhere. If you are starting your sentences for output with uppercase then try to follow it everywhere. The same is true about comments and constructs like to get a sum, to find a product, to divide. Use single ubiquitous style for everything.

Function return types

If you don't want to return anything from your function it should be void. All your calc functions are ints (but you don't call return operator) and you are not using return values. So all your calc functions should be void.

Redundant core2 function

Also core2 function is not needed here, you can use main directly. But C++ specs prohibits this behaviour although this works fine in most compilers. So we can replace core2 recursion with infinite loop in main.

So if we take into account all above notes code will look like this

#include <iostream>
#include <string>
using namespace std;

// Now we have only primitive one-liner arithmetic functions
// with double return types

double add(double a, double b) { return a + b; }

double subtract(double a, double b) { return a / b; }

double multiply(double a, double b) { return a * b; }

double divide(double a, double b) { return a / b; }

void core2() {
    string choice;
    cout << "Would you like to multiply, divide, add, or subtract? (typer in lowercase)" << endl;
    cin >> choice;

    // Choosing correct action name to output
    string result_name;

    if (choice == "add") {
        result_name = "sum";
    } else if (choice == "subtract") {
        result_name = "difference";
    } else if (choice == "multiply") {
        result_name = "product";
    } else if (choice == "divide") {
        result_name = "quotient";
    } else { // This block also performs validation of input parameter
        result_name = ""; // Just to prevent compiler error due to undeclared variable
        cout << "USER ERROR" << endl << "you typed in something wrong, try again." << endl;
        return; // end execution here
    }

    // Entering numbers in single place
    double a;
    double b;
    cout << "Enter two numbers to get the "<< result_name << "." << endl;
    cin >> a >> b;

    double result;

    if (choice == "add") {
        result = add(a, b);
    } else if (choice == "subtract") {
        result = subtract(a, b);
    } else if (choice == "multiply") {
        result = subtract(a, b);
    } else {
        result = divide(a, b);
    }

    // Outputting result in single place
    cout << "The " << result_name << " is " << result << "." << endl;
}

int main() {
    while (true) {
        core2();
    }
}

Further improvement will use more advanced techniques and relatively new C++11 features.

You need some way to map string and function, so for this we will use std::map as dictionary and std::function as polymorphic function wrapper. Also lambdas will be use to pass anonymous functions here as parameters. struct will be here used as container to store calculation function and result description.

#include <iostream>
#include <string>
#include <functional>
#include <map>
using namespace std;

struct CalculationTechnique {
    std::function<double (double,double)> Function;
    string ResultName;
};

void core2() {
    string choice;
    cout << "Would you like to multiply, divide, add, or subtract? (typer in lowercase)" << endl;
    cin >> choice;

    // Filling our dictionary
    std::map<string, CalculationTechnique> calculation_mapping = {
        { "add", CalculationTechnique { [](double a, double b) -> double { return a + b; }, "sum" } },
        { "subtract", CalculationTechnique { [](double a, double b) -> double { return a - b; }, "difference" } },
        { "multiply", CalculationTechnique { [](double a, double b) -> double { return a * b; }, "product" } },
        { "divide", CalculationTechnique { [](double a, double b) -> double { return a / b; }, "quotient" } }
    };

    // if no value found in dictionary
    if (calculation_mapping.count(choice) == 0) {
        cout << "USER ERROR" << endl << "you typed in something wrong, try again." << endl;
        return;
    }

    CalculationTechnique technique = calculation_mapping.at(choice);

    double a;
    double b;
    cout << "Enter two numbers to get the "<< technique.ResultName << "." << endl;
    cin >> a >> b;

    cout << "The " << technique.ResultName << " is " << technique.Function(a, b) << "." << endl;
}

int main() {
    while (true) {
        core2();
    }
}


A JavaScript isEven() function, defined recursively

The solutions are nowhere near equivalent.

You're using the remainder operator %, when the whole point - I assume - is to not do that (for the purposes of the exercise - in any other case, definitely use %).

The official solution only knows how to answer true/false for the numbers 0 and 1. For any other input, it uses recursion to reduce the input all the way to either 0 or 1. It also flips negative numbers, in order to get those to 0 or 1*.

Your solution answers immediately for any positive, even number, without recursion. So you're sidestepping the whole exercise. And your code ends up making little sense, since, if you can answer true immediately, it follows that you can answer false immediately too. Those are the only possible return values, so if it's not true it logically must be false. Since you're not recursing for the first case, why would you bother to recurse for the second one?

In addition, your code treats all negative numbers as odd, unlike the official solution. And math in general.

To put all this another way: The official solution approaches the problem with this knowledge:

0 is even
1 is odd
We don't know anything about the parity of other numbers
But any number can be reduced to either 0 or 1 by repeatedly subtracting 2 and/or flipping the sign if the number's negative.

Hence the need to recurse for numbers that are not 0 or 1.

Your approach says:

Numbers that can be cleanly divided by 2 are even (which is cheating)
Negative numbers are odd (which is wrong)
Any other number becomes negative if you keep subtracting 2

From the last point follows that any number that is not cleanly divisible by 2 is automatically an odd number. But you code doesn't make this leap, and instead uses (pointless) recursion.

Neither solution is by any means a good solution for determining the parity of a number(!), but the point (I assume, without knowing the context of the problem description) is to use recursion to drill down to something that can be answered categorically for specific numbers, i.e. 0 is even, 1 is odd. Your solution answers for sets of numbers, i.e positive even numbers and negative numbers.

*) For all of this we're assuming the input will always be a whole number, and not something else. Yes, you can do input validation, but that's beyond the scope of the exercise and this review


Switch statements can often be a sign that you need an extended class. Doctrine supports Inheritance Mapping. With some liberal re-factoring I created a PersonalLibrary and PurchasedLibrary, each which extend "Library". The various classes might look like this:

/**
 * @Entity(repositoryClass="LibraryRepository")
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="libraryType", type="string")
 * @DiscriminatorMap({1 = "PurchasedLibrary", 2 = "PersonalLibrary"})
 */
class Library
{
    //abbreviated class. add the properties and setters/getters as needed

    /**
     * @param \Smoovi\UserBundle\Entity\User $user
     * @param null|Library $parent
     */
    public function __construct(User $user, Library $parent = null)
    {
        $this->setUser($user);
        $this->setParent($parent);
        $this->setIndex(1);
    }

    public function setUser(User $user)
    {
        $this->user = $user;
        $this->setName($user->getFirstname()."'s Library");
    }
}

class PurchasedLibrary extends Library
{
    public function __construct(User $user, Library $parent = null)
    {
        parent::__construct($user, $parent);
        $this->setLibraryType(1);
    }

    public function setUser(User $user)
    {
        $this->setUser($user);
        $this->setName('Objects');
    }
}

class PersonalLibrary extends Library
{
    public function __construct(User $user, Library $parent = null)
    {
        parent::__construct($user, $parent);
        $this->setLibraryType(2);
    }

    public function setUser(User $user)
    {
        $this->setUser($user);
        $this->setName('Purchases');
    }
}

class LibraryRepository extends EntityRepository
{
    /**
     * Get a user's library. If unable to create, return null.
     *
     * @param \Smoovi\UserBundle\Entity\User $user
     * @param int $type
     * @return null\Library
     */
    public function getOrCreateLibrary(User $user, $type)
    {
        $parent = $this->getOrCreateParentLibrary($user);

        $sub = $this->findOneBy(array(
            'user' => $user,
            'parent' => $parent,
            'libraryType' => $type
        ));
        if (! $sub) {
            $sub = $this->createNewLibrary($user, $type, $parent);
            if (! $sub) {
                return null;
            }
        }

        $this->persist($sub);

        return $sub;
    }

    public function createNewLibrary(User $user, $type, $parent = null)
    {
        switch ($type) {
            case 1:
                return new PersonaLibrary($user, $parent);
                break;
            case 2:
                return new PurchasedLibrary($user, $parent);
                break;
        }

        return null;
    }

    private function getOrCreateParentLibrary(User $user)
    {
        $parent = $this->findOneBy(array(
            'user' => $user,
            'parent' => null,
            'libraryType' => null,
        ));
        if (! $parent) {
            $parent = new Library($user);
        }

        return $parent;
    }
}

Notes:

I'm using a Library Repository instead of a Library Manager. It's how I'd do it but, your LibraryManager may be just fine too.
I moved much of the behavior (deriving name, etc) into the setters of the Entities. This free's your Manager/Repository from this concern.
I added user and parent to the base Library Entity constructor. I'm assuming that in your domain, a Library must have a user.
It seems odd that "Index" is always 1
It seems odd that a "Top Level" table does not seem to be purchased or personal.
I would not flush the entity manager inside the those methods. Instead, I would let my calling code do it. The reason is that you may have other db operations to perform along with these. Postponing the flush operation allows you to do everything in 1 transaction.
I renamed your method names to indicate that there could be side effects as a result of calling the method (get OR create).
No need to persist parent. Persisting the sub (assuming associations are set up) should persist the parent.
I think you'll always need at least 1 switch in there somewhere that is used to construct the new entity based on it's type.


Same method to export different txt files C#

I don't have much reputations to comment so trying to help for what I know and modified your code according to the need -

There are two issues I observed -

The below line in your code -

  var userPath = Path.Combine(dir,Enum.GetName(typeof(exportByName),0),".txt");

will generate the output "directory+name of array\.txt" instead of
  "directory+name of array+.txt"

You mentioned the point saying "the file is not created", actually your code
is just returning the path using Path.Combine you need to create file for each of the ENUM values using the File.WriteAllText method.

I have modified your code and placed below. Please check

class Program
    {
        enum exportByName { Client, Appointment, Address, Location, Historic }

        static string askPath(int count)
        {
            var dir = "";

            do
            {
                Console.Clear();
                Console.Write("Insert path to export the txt file: ");
                dir = Console.ReadLine();
            } while (String.IsNullOrEmpty(dir));

            var userPath = Path.Combine(dir, Path.GetFileName((Enum.GetName(typeof(exportByName), count))) + ".txt");
            return userPath;
        }
        static void Main(string[] args)
        {

            for (int i = 0; i < 4; i++)
            {
                var path = askPath(i);
                if (!File.Exists(path))  // if it doesn't exist, create

                    File.WriteAllText(path, "add text here");
            }
        }

    }

Hope this helps!


It looks like row is simply a hash, but it has various value combinations that are significant.

You could refactor the detection of those combinations, for example by creating a class based on the row that has an attribute for #transaction_type ...

class Row
  def initialize(row)
    @row = row
  end

  def sender_blz
    row['SENDER_BLZ']
  end

  def receiver_blz
    row['RECEIVER_BLZ']
  end

  def umsatz_key
    row['UMSATZ_KEY']
  end

  def transaction_type
    return "AccountTransfer" if sender_blz   == "00000000" && receiver_blz == "00000000"
    return "BankTransfer"    if sender_blz   == "00000000" && umsatz_key == "10"
    return "Lastschrift"     if receiver_blz == "70022200" && umsatz_key == "16"
    false
  end
end

Then your method becomes

Row.new(row).transaction_type

I would rather see magic strings like "00000000" replaced with constants, and conditions like sender_blz == "00000000" replaced with methods that give a name to the condition, like:

def sender_not_specified?
  sender_blz == NOT_SPECIFIED
end

... thus you would have something like ...

  def transaction_type
    return "AccountTransfer" if sender_not_specified? && receiver_not_specified?
    return "BankTransfer"    if sender_not_specified? && something_about_umsatz?
    return "Lastschrift"     if receiver_not_specified? && something_else_about_umsatz?
    false
  end


Building a simple singly-linked list in C++11

First, note that the only real difference between a struct and a class is the default accessibility: in a class everything is private by default, and in a struct everything is public by default. That's literally the only difference between the two.

In any case, some of your code can be simplified somewhat. For example, your insert can be reduced to just this:

void insert(Node*& head, int data) {
    head = new Node{data, head};
}

It's usually better to initialize rather than construct something uninitialized, and then assign a value anyway, so this is sort of a double-win.

I'd also prefer to use a for loop to print the list, and just a new-line where you want to print a new-line:

void print_list(Node* list) {
  Node* p {list};
  std::cout << "Printing list:\n";
  if (p)
  {
    std::cout << p->data;
    for (p=p->next; p != nullptr; p=p->next)
      std::cout << " -> " << p->data;
  }
  std::cout << "\n";
}

In this case, I'd restructure the code a bit to treat the list being non-null as a pre-condition to print_list and enforce that up-front:

void print_list(Node* list) {
  if (list == nullptr)
      return;
  std::cout << "Printing list:\n";
  std::cout << list->data;
  for (Node *p{list->next}; p != nullptr; p=p->next)
    std::cout << " -> " << p->data;
  std::cout << "\n";
}

The next steps I can see would involve the sort of re-vamping you don't seem to want right now--turning the linked list into a full-blown class of its own that supports iterators and such. This does have a tremendous advantage though: right now, your linked list only supports inserting items, then printing an entire linked list. If anybody wants to do anything else, they need to implement it entirely on their own, and know all about the internal details of the linked list to do it.

Along with that, you'd probably want to make it a generic container, so you can use it to store any data type, not just int.

This way, you can immediately support essentially all code that knows how to work with a collection that supports (in this case) forward iterators. You'd probably just eliminate print_list entirely, as it becomes just an application of std::copy from a list to (for example) an infix_iterator.

This is (IMO) much cleaner in general. In particular, it separates concerns much more cleanly: the linked list can concentrate solely on linked-list "things", and not worry about things like I/O as it does now.


this scope for parent object within inner object

I understand that you are just experimenting with closures, because your code should be a simple geter like that...

var object = {
　　name : 'foo',
　　getName : function(){ //closure
        return {
            a : 111,
            b : this.name, // variable th is avaliable in the inner scope
            c : function(){
                return this.b;
            }
        }
 　}
};

object.getName().b  // 'foo'

This does the same as your example:

var object = {
　　name : 'foo',
　　getName : (function(){ //closure
         var th=this;     // a new var introduced in a closure
　　　　　 return function(){
            return {
                a : 111,
                b : th.name, // variable th is avaliable in the inner scope
                c : function(){
                    return this.b;
                }
            }
       }();
 　})
};

object.getName().b  // 'foo'

[edit]

this in JS depends on where the function is called as well, so if you want a nice encapsulation Try this:

var object = {}
(function(){

  var _name='foo';

  object.getName=function(){
    return _name;
    }
});


Removing a specific key of ModelState for a specific controller's method

While your approach might work, I consider it a hack. The preferred solution would be to create different models for each request so that the user does not have a chance of passing values that might not only not be required but even be forbidden.

Your new entities could be:

class NewUser
{
    public string Name { get; set; }
}

Where there are is no Id if the AIP does not require it.

It is a very bad idea to expose your database models to the caller. Create more specific models and map their properties to your database entities.

If you let the user the possibility of passing anything he wants, you would need to validate even more values to be sure he does not try to do something else than you want him to.

One such example could be when you have an API for updating User.Name but that user has a navigation property Books and the caller sends you some books too that will also get updated... just because he can. This might cause you a lot of trouble.