Deleting temporary rows and columns from 21-sheet workbook

Portland Runner gave some good hints in the comments. Your selection and view changes do not add any value to what you want to achieve. I was able to remove all of them without issues. When doing macro-based Excel manipulation, you should always consider:

Setting Application.ScreenUpdating to False
Setting Application.Calculation to xlManual
Setting Application.EnableEvents to False
Resetting all of these values when you have completed the work

Of course, there will be exceptions, but these should be rare.

Always remember Option Explicit in VBA

Looking at absolute values:

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    xWs.DisplayPageBreaks = False
    xWs.UsedRange.Value = xWs.UsedRange.Value
Next

This can simply be:

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.UsedRange.Value = xWs.UsedRange.Value
Next

Cleaner, easier to see what it does, and easier to maintain.

Looking at Column B conditionals:

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    xWs.DisplayPageBreaks = False
    Firstrow = xWs.UsedRange.Cells(1).Row
    Lastrow = xWs.UsedRange.Rows(xWs.UsedRange.Rows.count).Row
    For Lrow = Lastrow To Firstrow Step -1
        With xWs.Cells(Lrow, "B")
            If Not IsError(.Value) Then
                If .Value = "0" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
Next

Can become:

For Each xWs In Application.ActiveWorkbook.Worksheets
    Firstrow = xWs.UsedRange.Cells(1).Row
    Lastrow = xWs.UsedRange.Rows(xWs.UsedRange.Rows.count).Row
    For Lrow = Lastrow To Firstrow Step -1
        With xWs.Cells(Lrow, "B")
            If Not IsError(.Value) Then
                If .Value = "0" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
Next

But I see repetition here. You can save your self a small loop. Admittedly, in the example you gave not a big issue but still a good practice to have.

Combining the loops - take note of the order in which I have done this. Do the most work first, and then do the simple clean-up. You could do it the other way (unless the xlError gets converted to a value on the way through?) but considering how much work is done in each step and how each step impacts on the amount of future work is a good habit.

For Each xWs In Application.ActiveWorkbook.Worksheets
    Firstrow = xWs.UsedRange.Cells(1).Row
    Lastrow = xWs.UsedRange.Rows(xWs.UsedRange.Rows.count).Row ' this is yet another different way I have seen to get the last row!
    For Lrow = Lastrow To Firstrow Step -1 ' Good that you know to go backwards.
        With xWs.Cells(Lrow, "B")
            If Not IsError(.Value) Then
                If .Value = "0" Then .EntireRow.Delete
            End If
        End With
    Next Lrow
    xWs.UsedRange.Value = xWs.UsedRange.Value ' Good that you know the simple way to convert formulas to values.
Next

Deleting extra columns - I see a lot of repetition here, and room for a subroutine.

Private Sub Delete78(xWs as Worksheet) 'Sheet could also include a Chart sheet
    xWS.Columns(8).EntireColumn.Delete
    xWS.Columns(7).EntireColumn.Delete
End Sub

Interestingly, you could also do Col7.Del, and then Col7.Del again to achieve the same effect! But at least the way you have written it shows the intent to remove the two columns.

You main part of the code then becomes:

Delete78 Sheets("IP-FSW")
Delete78 Sheets("IP-2070")
Delete78 Sheets("IP-MNTR")
Delete78 Sheets("IP-BBS")
Delete78 Sheets("IP-DET")
Delete78 Sheets("IP-TTR")
Delete78 Sheets("IP-CCTV")

Still some repetition - and this could be fixed as well. But that can be another day. Or perhaps now. Because your last code block seems different but is really the same. So let us try a new subroutine.

Private Sub DeleteColumnBlock(xWs as Worksheet, LastColumn as Long, FirstColumn as Long) ' Get the user to enter the values in a logical order. I chose this way.
    Dim ColIterator as Long
    ' Do some input validation. If they have entered bad values, fix it.
    For ColIterator = LastColumn to FirstColumn Step -1
        xWs.Columns(ColIterator).EntireColumn.Delete
    Next ColIterator
End Sub

Because we are dealing with a contiguous block, you could also do the slightly more obscure - same effect, but slightly harder to see at a glance what you intend to do. Add some good comments if you intend to do this!

For ColIterator = FirstColumn to LastColumn
    xWs.Columns(FirstColumn).EntireColumn.Delete ' continually remove a column until the right number have been removed.
Next ColIterator

Your main part of that entire block then becomes:

DeleteColumnBlock Sheets("IP-FSW"), 8, 7
DeleteColumnBlock Sheets("IP-2070"), 8, 7
DeleteColumnBlock Sheets("IP-MNTR"), 8, 7
DeleteColumnBlock Sheets("IP-BBS"), 8, 7
DeleteColumnBlock Sheets("IP-DET"), 8, 7
DeleteColumnBlock Sheets("IP-TTR"), 8, 7
DeleteColumnBlock Sheets("IP-CCTV"), 8, 7
DeleteColumnBlock Sheets("IP-Unassigned"), 16, 8

Summary

Turn off the parts of Excel that you don't need when doing grunt
work.
Try to run through a loop only once, don't repeat your loops
unless it is really really necessary.
DRY (don't repeat yourself) - repetition is a sign that you can
modularise some code making it easier to maintain.
Use explicit addressing, avoid Active and Select unless there is
no other way (e.g. copying sheets to a new workbook is a subroutine,
not a function so ActiveWorkbook is the only way to immediately
reference that new workbook).
-- If you do Activate or Select, make sure your following code is    actually using those elements.
-- And then consider if you can already reference it explicitly and do    so!

Addendum

In my examples above, I provided a very mechanistic way of deleting columns (based on the OP code). Two more ways to do this without using a loop are to set a range:

e.g. xWS.Range(xWS.Cells(1,7), xWS.Cells(1,8).EntireColumn.Delete
Setting a union of the columns, and then deleting


Rearranging numbers of an array like a wave

Few observations.

You don't need to maintain swap2 separately, it is always swap1 + 1, so can be simply declared inside the loop's body.
Your boundaries check inside the loop body is redundant, loop condition alone is enough.
You're probably performing too many int-to-Integer and back conversions. Even more, the question deals with arrays, you don't need to pre-convert the argument into a list. Accept, process and return an array of plain ints.


Naming

Helper, although very common, is too generic as class name. Imagine it in a package with two dozens of other classes, how would you have a hint on what it is supposed to do by browsing the package? If it was named something like PdfAnalyzeHelper or PdfProcessingHelper, that would be better.
Looking at the name of the method getURL(args), I was expecting to find a return value instead of void, which was confusing. The prefix get* in method names is often used for getters. Since this method does not return anything and executes some URL processing, that should be called, for example, replaceReportIdInUrls(args).

SRP

The single responsibility principle seems to be violated in this method. I see three distinct things done:

Loading a PDF file.
Reading the file and replacing values in URLs.
Saving a new PDF file.

I'd suggest to split it into three distinct methods. It will be easier to maintain and reuse, if this is intended. Or, since the I/O with PDDocument is very concise, remove it from the method body and change the signature to

public static PDDocument replaceReportIdInUrls(PDDocument doc,
                                               String reportIdOld,
                                               String reportIdNew);

try-with-resources

The I/O with finally { doc.close(); } is plain old before-Java-7 style. It can be simplified for

try (PDDocument doc = PDDocument.load(oldpdf)) {
     // method body
} catch (IOException | COSVisitorException e) {
     // multicatch is also helpful!
}

This shortens the method for at least 12 lines!

Generics

The version of PDFBox that you use seems to be a legacy one, PDDocumentCatalog.getAllPages() somehow returns an unbound List.
In order to (at least) avoid compilation warnings, type bounds should be added, for example:

List<?> allPages = doc.getDocumentCatalog().getAllPages();

According to the javadoc, the list should contain PDPage objects, so if you dare rely on it, you can try a cast to List<PDPage>.

The same comment concerns the next List of annotations. Strangely, the javadoc describes it as typed, so only <PDAnnotation> should be added to the declaration.

For Loops

The j index of the inner loop is not reused, so it would be simpler to rewrite the loop:

for (PDAnnotation annotation : annotations) { ... }

and this will make useless the call annotations.get(j);

The same is about the outer loop, but since the i index is reused for the output, it can be kept.

Validation

The line

String reportID = oldURL.substring(oldURL.lastIndexOf("=") + 1, oldURL.length());

is not secured against the case when the URL does not contain the "=" character. oldURL.lastIndexOf("=") may return -1, in such case a StringIndexOutOfBoundsException will be thrown.

By the way, no validation at all is done for the method input params. What happens if one of them is null or empty?


Comparing dates (without the time part) in Java

It's an interesting, simple approach.

But you don't need new Long objects. Better use primitive types instead.

In fact, as @njzk2 pointed out in a comment,
you don't need long at all, as dates in yyyyMMdd format are alphabetically sorted, you can use simple String comparison.

It's good you mention in comments that you create a SimpleDateFormat instance inside the method for thread safety.
Another common solution in such situations is to use a ThreadLocal.
You can wrap a SimpleDateFormat instance in a ThreadLocal so that all threads will have their own copy, eliminating thread safety issues.

Last but not least, "math" is a poor name for a date formatter object.

Putting my suggestions together:

private static final ThreadLocal<DateFormat> dateFormatThreadLocal = new ThreadLocal<DateFormat>() {
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};

public static int compareDates(Date date1, Date date2) {
    DateFormat dateFormat = dateFormatThreadLocal.get();
    return dateFormat.format(date1).compareTo(dateFormat.format(date2));
}


The one thing different between your implementation and jquery.on is that jQuery allows you to bind on any element. One reason for that is performance. If on a deep tree, it would take a while for it to reach the delegate target. That's one reason jquery.live was deprecated.

Another is that your eventObject only accepts one callback per selector. If I were to register another callback under the same selector, then it would overwrite whatever was previously registered. Consider creating an array on the fly and push to it. You will need to change the way your code calls callbacks.


Backbone/Marionette form with list of inputs

Answering my own question. A View's Model represents "state", not data. This is a subtle distinction that wasn't apparent to me at first. The Collection should match the View, blank values and all.

When it comes time to save the list, the Collection's toJSON method can be overridden to omit any blank models.

I updated my original jsfiddle to show values being saved on blur.

var Person = Backbone.Model.extend();

var People = Backbone.Collection.extend({
  model: Person,
  toJSON: function() { /*filter out empty models*/}
});

var PersonView = Marionette.ItemView.extend({
  ...
  events: {
    'blur input': 'onChange', //calls model.set('name', input value)
  },
  triggers: {
    'click .del-name': 'remove:form:row' //calls collection.remove(...)
  },
  ...
});

var FormView = Marionette.CompositeView.extend({
  events: {
    'click @ui.addBtn': 'addFormRow' //calls collection.add({name: ''})
  },
  collectionEvents: {
    add: 'onRowAdded'  //rerender first row to show delete button
  },
  ...
});


// undefined symbol: lua_rawlen

This happens because there is no such function in Lua 5.1 C API. As stated by documentation lua_objlen is preffered way to get table length.

FYI lua_rawlen function first appeared in Lua 5.2.

It is very handy to check Lua Reference manual to see availiable C API for particular Lua version.

Serialization with zero latency

Wow, that title stands out. Let me explain what I mean: serialization with zero latency means there is no serialization at all.

Watch out: it heavely depends on the origin of your table.

The caveats:

you must control the table creation
only inserts, no removes

If this is the case, follow on:

As you stated your table is actually an array of Lua numbers. In C Lua number is lua_Number which is probably a double value.

We can create a custom table implementation to only store Lua numbers in it.
The table will be continuos memory with lua_Number members in it.

typedef struct {
    lua_Number *items;
    size_t len; // number of entries in items
    size_t cap; // maximum `len` value before we will `realloc(items)`
} fasterarray;

To provide fasterarray we'll use lua_newuserdata. It will allocate memory that will be watched by Lua garbage collector. In particular when there is no more references the allocated userdata will be collected.

static int new(lua_State *L) {
    fasterarray *fa = lua_newuserdata(L, sizeof(fasterarray));
    luaL_getmetatable(L, NAME); // <-- setting metatable, see below
    lua_setmetatable(L, -2);    // <--
    fa->len = 0;
    fa->cap = 8;
    fa->items = calloc(fa->cap * sizeof(lua_Number), 1);
    return 1;
}

Insert function will realloc items when more space is needed.

static int insert(lua_State *L) {
    fasterarray *fa = lua_touserdata(L, 1);
    lua_Number num = lua_tonumber(L, 2);
    if (fa->len == fa->cap) {
        fa->cap *= 2;
        fa->items = realloc(fa->items, fa->cap * sizeof(lua_Number));
        assert(fa && fa->items);
    }
    fa->items[fa->len++] = num;
    return 0;
}

Important part of this implementation is garbage collection. userdata will be collected by Lua automagically, but the memory behind items must be freed directly in C. To handle this we will use __gc metatable method.

static int gc(lua_State *L) {
    fasterarray *fa = lua_touserdata(L, 1);
    if (fa && fa->items) free(fa->items);
    printf("gc\n");
    return 0;
}

Full example:

fasterarray.c

#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

#define NAME "fasterarray"

typedef struct {
    lua_Number *items;
    size_t len;
    size_t cap;
} fasterarray;

static int new(lua_State *L) {
    fasterarray *fa = lua_newuserdata(L, sizeof(fasterarray));
    luaL_getmetatable(L, NAME);
    lua_setmetatable(L, -2);
    fa->len = 0;
    fa->cap = 8;
    fa->items = calloc(fa->cap * sizeof(lua_Number), 1);
    return 1;
}

static int gc(lua_State *L) {
    fasterarray *fa = lua_touserdata(L, 1);
    if (fa && fa->items) free(fa->items);
    printf("gc\n");
    return 0;
}

static int insert(lua_State *L) {
    fasterarray *fa = lua_touserdata(L, 1);
    lua_Number num = lua_tonumber(L, 2);
    if (fa->len == fa->cap) {
        fa->cap *= 2;
        fa->items = realloc(fa->items, fa->cap * sizeof(lua_Number));
        assert(fa && fa->items);
    }
    fa->items[fa->len++] = num;
    return 0;
}

int luaopen_fasterarray(lua_State *L) {

    // fasterarray metatable
    luaL_newmetatable(L, NAME);
    luaL_register(L, NULL, (luaL_Reg []) {
        {"__gc", gc},
        {NULL, NULL}
    });

    // exported funcs
    luaL_register(L, NAME, (luaL_Reg []) {
        {"new", new},
        {"insert", insert},
        {NULL, NULL}
    });
    return 1;
}

example.lua

require"fasterarray"

local ar = fasterarray.new()
local i = 700000
while i > 0 do
        fasterarray.insert(ar, i)
        i = i - 1
end


Vue.js component for adding/removing items

It looks like the code makes good use of basic VueJS concepts and practices- using computed properties, binding values, conditional display with v-if, etc.

I also like the application of arrow functions, promise handling, etc.

I see there is a key attribute bound to the list items (i.e. v-bind:key="wrestler.id"). Correct me if I am wrong but that doesn't appear to be an attribute of <li>. What is that used for? Edit: Oh yes, thanks for reminding me about the key attribute for list editing

Then in the addWrestler() method, there are two .then() callbacks. Is there a reason not to move the three lines in the second callback into the first?

axios.get(this.action, { name: this.name })
    .then((response) => {
        this.wrestlers.push(response.data.data);
        this.busy = false;
        this.name = '';
        this.$refs.name.focus();
    })
    .catch(...)

If you really wanted to shorten the code for the promise callbacks, you could abstract those into methods.


Quite frankly it seems that you did not do what was asked from you.

The text above assign gives you the requirements

    // Assign value val to interval [keyBegin, keyEnd).
    // Overwrite previous values in this interval.
    // Conforming to the C++ Standard Library conventions, the interval
    // includes keyBegin, but excludes keyEnd.
    // If !( keyBegin < keyEnd ), this designates an empty interval,
    // and assign must do nothing.

So you have to find all elements in the map that are in the range [keyBegin, keyEnd) and assign val to them. Then you should insert keyBegin and keyEnd with the value val into the map.

Actually you are quite close to what was asked with the calls to lower_bound

    void assign(K const& keyBegin, K const& keyEnd, V const& val) {
        // keyBegin < keyEnd indicates an empty interval, so the function simply returns
        if (!(keyBegin < keyEnd))
            return;

        ....
    }

This is already a problem as the comment is incorrect. It should read keyEnd < keyBegin

        auto begin_lower_iter = m_map.lower_bound(keyBegin);
        auto end_upper_iter = m_map.upper_bound(keyEnd);

The first call is obviously correct. However, the second call is the wrong one. upper_bound returns the first element that is greater than the key. Now consider if keyEnd is in the map. As the interval is half opened you would have to decrement twice in that case and once if it is not in the map.

Rather than that you can simply use lower_bound here too

        auto begin_iter = m_map.lower_bound(keyBegin);
        auto end_iter = m_map.lower_bound(keyEnd);

Now we have to consider the bounds. First you should check, whether keyBegin is already in the map. Otherwise you should insert it so that the left boundary is inclusive. Note that in that case we can use begin_iter as a hint so that the complexity is an amortized constant

        if (begin_iter->first != keyBegin) {
            begin_iter = m_map.insert(begin_iter, val);
            // The element at begin_iter already has the correct value so increment
            ++begin_iter;
        }

It is slightly different for the upper boundary, as that is exclusive. As far as i understand it, that means that you should insert an element with the value the interval had previously so that it is the inclusive left border of the new interval.

If end_iter is at keyEnd it already has the correct value and we do not have to do anything. However if it is not in the map, then we have to insert the value of the previous element at position keyEnd

        if (end_iter->first != keyEnd) {
            V const& oldVal = std::prev(end_iter, 1)->second;
            end_iter = m_map.insert(end_iter, oldVal);
        }

Now to a completely different topic. As you might have seen insert returns an updated iterator. While there is no iterator invalidation in std::map,i would not risk it. So the insertion should happen right after you get the iterator.

        auto begin_iter = m_map.lower_bound(keyBegin);
        if (begin_iter->first != keyBegin) {
            begin_iter = m_map.insert(begin_iter, val);
            // The element at begin_iter already has the correct value so
            ++begin_iter;
        }

        auto end_iter = m_map.lower_bound(keyEnd);
        if (end_iter->first != keyEnd) {
            V const& oldVal = std::prev(end_iter, 1)->second;
            end_iter = m_map.insert(end_iter, oldVal);
        }

Also this is still not correct. Lets assume begin_iter was not less that the first element in the map smaller than keyEnd. In that case we would have overwritten the original value of the -larger- interval. Therefore, the insertion of the upper bound needs to happen first.

Now that we handeled the borders, we should update the elements int the range

        while(begin_iter != end_iter) {
            begin_iter->second = val;
            ++begin_iter;
        }

Finally, there is still an elephant in the room. While the whole file seems to be not fully consistent, the arguments to the function are camelCase. Yet you named your variables using snake_case. For me that is already a minus as you do not adopt to the existing codebase and inconsistent naming is a constant source of confusion and a huge drain on mental capacity.

So lets put it together

    void assign(K const& keyBegin, K const& keyEnd, V const& val) {
        // keyBegin < keyEnd indicates an empty interval, so the function simply returns
        if (!(keyBegin < keyEnd)) {
            return;
        }

        // Search for the upper bound and if necessary include a border element
        // with the value of the old interval
        auto endIter = m_map.lower_bound(keyEnd);
        if (endIter->first != keyEnd) {
            // As the intervals are half open we need to take the value of the left element and insert it at keyEnd
            V const& oldVal = std::prev(endIter, 1)->second;
            endIter = m_map.insert(endIter, oldVal);
        }

        // Search for the lower bound and if necessary include the element
        auto beginIter = m_map.lower_bound(keyBegin);
        if (beginIter->first != keyBegin) {
            beginIter = m_map.insert(beginIter, val);
            // The element at begin_iter already has the correct value so
            ++beginIter;
        }

        // Update the values within the range [beginIter, endIter)
        while(beginIter != endIter) {
            beginIter->second = val;
            ++beginIter;
        }
    }


How can I reduce the number of nested if statements in this code?

I assume that the code in the question is a method. If not extract it out to a method.

boolean appUpdatesAccepted = Parameters.load(mContext).getUpdateType() == UpdateType.BOTH
        || Parameters.load(mContext).getUpdateType() == UpdateType.APPLICATION;
boolean paramUpdatesAccepted = Parameters.load(mContext).getUpdateType() == UpdateType.BOTH
        || Parameters.load(mContext).getUpdateType() == UpdateType.PARAMETERS;

I'd start with removing some duplication here.

UpdateParameters updateParameters = Parameters.load(mContext);

...

final UpdateType updateType = updateParameters.getUpdateType();
boolean appUpdatesAccepted = updateType == UpdateType.BOTH
        || updateType == UpdateType.APPLICATION;
boolean paramUpdatesAccepted = updateType == UpdateType.BOTH
        || updateType == UpdateType.PARAMETERS;

I'm not familiar with Android, so UpdateParameters and UpdateType types could be something else.
If you reorder the boolean variables you can find some more duplication:

final boolean appUpdatesAvailable = availableUpdates
    .containsKey("application");
final boolean appUpdatesAccepted = updateType == UpdateType.BOTH
    || updateType == UpdateType.APPLICATION;

final boolean paramUpdatesAvailable = availableUpdates
    .containsKey("parameters");
final boolean paramUpdatesAccepted = updateType == UpdateType.BOTH
    || updateType == UpdateType.PARAMETERS;

This could be extracted out to a method:

private boolean isUpdateAvailable(
        final Map<String, String> availableUpdates,
        final UpdateParameters updateParameters,
        final UpdateType updateType, final String updateKey) {
    final UpdateType availableUpdateType = updateParameters
        .getUpdateType();
    final boolean appUpdatesAvailable = availableUpdates
        .containsKey(updateKey);
    final boolean appUpdatesAccepted =
        availableUpdateType == UpdateType.BOTH
        || availableUpdateType == updateType;
    return appUpdatesAvailable && appUpdatesAccepted;
}

Usage:

final boolean tryApplicationUpdate =
    isUpdateAvailable(availableUpdates, updateParameters,
        UpdateType.APPLICATION, "application");
final boolean tryParametersUpdate =
    isUpdateAvailable(availableUpdates, updateParameters,
        UpdateType.PARAMETERS, "parameters");
if (tryApplicationUpdate) {
    ...
} else if (tryParametersUpdate) {
    ...
} else {
    ...
}

It's also possible to extract out the first two if blocks to a method, they are very similar to each other:

private void downloadUpdateIfConfirmed(
        final boolean shouldConfirm,
        final Map<String, String> availableUpdates,
        final UpdateType currentUpdateType, final String updateKey) {
    final boolean shouldInstall = shouldConfirm ?
        confirmInstallUpdate(currentUpdateType) : true;
    if (shouldInstall) {
        downloadUpdate(currentUpdateType, availableUpdates.get(updateKey));
    } else {
        gotoNextActivity();
    }
}

Usage:

if (tryApplicationUpdate) {
    downloadUpdateIfConfirmed(shouldConfirm, availableUpdates,
        UpdateType.APPLICATION, "application");
} else if (tryParametersUpdate) {
    downloadUpdateIfConfirmed(shouldConfirm, availableUpdates,
        UpdateType.PARAMETERS, "parameters");
} else {
    ...
}

I'd move the shouldConfirm flag into the method (to reduce its scope, see Effective Java, Second Edition, Item 45: Minimize the scope of local variables); use guard clauses; create another method which calls gotoNextActivity() to remove its duplication:

public void update() {
    doUpdate();
    gotoNextActivity();
}

private void doUpdate() {
    mContext = this.getApplicationContext();
    final UpdateParameters updateParameters = Parameters.load(mContext);
    final UpdateMode updateInstallationMode =
        updateParameters.getUpdateMode();
    if (updateInstallationMode == UpdateMode.MANUAL) {
        return;
    }
    lblStatus.setText(getString(RString.checking_for_updates));
    final Error outUpdateError = new Error();
    final Map<String, String> availableUpdates =
        checkForUpdates(outUpdateError);

    final boolean tryApplicationUpdate =
        isUpdateAvailable(availableUpdates, updateParameters,
            UpdateType.APPLICATION, "application");
    final boolean tryParametersUpdate =
        isUpdateAvailable(availableUpdates, updateParameters,
            UpdateType.PARAMETERS, "parameters");
    if (tryApplicationUpdate) {
        downloadUpdateIfConfirmed(updateInstallationMode,
            availableUpdates, UpdateType.APPLICATION, "application");
        return;
    }
    if (tryParametersUpdate) {
        downloadUpdateIfConfirmed(updateInstallationMode,
            availableUpdates, UpdateType.PARAMETERS, "parameters");
        return;
    }
    lblStatus.setText(getString(RString.app_up_to_date));
}

private void downloadUpdateIfConfirmed(
        final UpdateMode updateInstallationMode,
        final Map<String, String> availableUpdates,
           final UpdateType updateType, final String updateKey) {
    final boolean shouldConfirm =
        (updateInstallationMode == UpdateMode.CONFIRM);
    final boolean shouldInstall = shouldConfirm ?
        confirmInstallUpdate(updateType) : true;
    if (shouldInstall) {
        downloadUpdate(updateType, availableUpdates.get(updateKey));
    }
}


Automapper - Mapping a nested collection to a list

When dealing with collections, the trick is always to set up a mapping of the items in the collections and never (well, I've never seen a case that needed) a mapping from one collection to another. That's the point of the generic.

The trick I always use is to work backwards, starting with a mapping between the types inside the collections and then going up a level. If one object needs to go up 2 levels, it's time to use ForMember to get to a nested property.

What you want to do in this case is to set up the following mappings:

Mapper.CreateMap<SourceObject, TargetObject>();
Mapper.CreateMap<SourceOuterObject, TargetOuterObject>()
    .ForMember(dest => dest.TargetList, opt => opt.MapFrom(src => src.SourceSet.SourceList);


You need to use the two Streams as, well, streams: read a manageable part of the input, transform it, write it to the output and repeat.

int bufferSize = 4096; // or whatever

char[] characters = new char[bufferSize];

using (var reader = new StreamReader(inFile))
using (var writer = new StreamWriter(inFile + ".NonAsciiChars"))
{
    while (true)
    {
        int read = reader.Read(characters, 0, characters.Length);

        if (read == 0)
            break;

        var replaced = Regex.Replace(new string(characters), pattern, string.Empty);

        writer.Write(replaced);
    }
}

Some notes about this code:

Notice the missing Close() calls: the whole point of using is safe closing of streams, and similar resources, so you don't need to close them twice.
This code (just like the original) creates a lot of garbage to be collected by the GC. Since your regex is actually very simple, it might be better to manually work directly with char[]s.
I used string.Empty instead of "". This makes it very clear that empty string was actually intended and it's not just “I started writing string and then forgot about it” bug.


In Go you have a choice as to whether you treat structs like an object with its own methods, and you have an object-oriented feel to your code, or you treat data like parameters, and you pass the data around in a more procedural format. Let's look at your first method first.

The ReviewData struct is a struct, and you've declared a method on it that has no parameters. The data required in the method comes from the instance of the struct itself, r.ShopID. The logic there is clear (as an aside .... semantically it's a bit ambiguous because, if you have an r instance, it seems like it should Exist... it's a bit odd to see logic like if abc.Exists() {... because if abc did not exist it seems like abc should be nil ;-)

Regardless, your first version of the code looks very natural to me if you're treating the ReviewData as an "object" with an object-oriented perspective.

The second version of the code is flawed in its current state. The problem is that the second version has the signature:

func (r *ReviewData) Exist(shpoID int64) bool {

but, inside the function, you never use r. Why is it a method on an instance that you never use the instance's data for? It should be just:

func Exist(shopID int64) bool {

(NB: I changed the spelling to be correct... you really should make sure the code works before submitting it to Code Review - broken code is frowned on, and code that does not compile is very frustrating. It could not have compiled with shpoID instead of shopID)

Anyway, the second version is good as a static type of procedure/function, instead of an object instance-based method.

So, depending on how you use the code, the general structure of other methods on ReviewData, and the business logic about whether you create an instance of ReviewData before the shopID exists, or not, determines whether you use the method based version (the first one), or the function version (the second one).

If you store the shopID on the ReviewData instance (and in no other places), then its better to use the first mechanism. If the shop ID is used in multiple places then it may be best to have a package for shops themselves, and then you code could look like if shops.Exists(id) .... (which is the second version).

Bottom line, the right solution depends on how your data is encapsulated, and how you reuse the code.


Bugs

In CountCoins:

print

... has no effect. The same applies to other parts of your code where you used this. If you meant to print a newline, use print() instead. You've also used print inconsistently, sometimes just leaving out the parentheses. Your tags include python-3.x, so you should fix that.

raw_input("")

... there's no such thing as raw_input in Python 3. I'm starting to think you've used a wrong tag.

Comparisons to True

Python automatically compares to True in if / elif / else / while statements. Therefore, you can shorten this:

while gameStart == True:

if spawn == True:

if spawnStart == True:

... to this:

while gameStart:

if spawn:

if spawnStart:

... what this also means is that instead of writing:

if wardrobeSpawn == False

... you can write:

if not wardrobeSpawn:

... which is shorter and more readable.

F-strings

Instead of doing:

print("You have: " + str(coins) + " coins")

You might want to use a so-called f-string:

print(f"You have {coins} coins")

This is easier for you and other developers.
f-strings are only available in Python 3.6 and later.

Functions

You seem to be using just one function. I suggest splitting the game up into several functions, perhaps like this:

def Level1():
    print("You wake up ...")

def Choice1()

def Choice2()

Styling

You should definitely read PEP8.
It states that you should, for example, use snake_case for variables and function names. Also, you should leave enough whitespace in between blocks of code to make it easier to read and manage. Really, take a look, it's a good read.


Javacript/jQuery animation makes text appear/disappear as if typed

For those who dont like typed.js, Modified code for the user code is.

Here,

content -> is the text that shows the typing effect.
speed ->  is the typing effect speed.   i  -> this will help in
iterating over the content till it reaches the content length.
timer  -> we use this variable to assign the setTimeout(), so
that after the text content is looped, we can use this variable to
clear timer. This  will prevent memory leakage.
intervalCount  ->
this variable is used to initialise how many times the content need
to toggle.

const content = 'Code Review'; // text content to show typing effect
const speed = 1000; // this is the typing speed
var i = 0;  // this is used to iterate over the text content
var timer = 0;  // this is used to set and clear timer. This will prevent memory leakage
var intervalCount = 0; // this is used to set no. of times typing effect should loop.

Here initially i will be 0, then it checks with the content length. If i < content.length, then it will add content[i] to the dom. After that i is incremented by 1, then a setTimeout() function is called. This will invoke the typeSetting once again, at this time i will 1 and it will print content[1]. This will loop untill i become the content length.

This condition will iterate over the text content and displays them.

if (i < content.length) {
        el.before(`<span class='typed-letter'>${content[i]}</span>`);
        i++;
        timer = setTimeout(function() {
          typeSetting(intervalCount)
        }, speed);
      }

Now the else part, here first it will clear the timer ( Which will prevent the memory leakage ), then it decrement the intervalCount, check for the intervalCount is  > 0, then set i = 0 ( this will help in printing the string from begining ). Again in a setTimeout() is called. At this time, the printed content is removed and starts printing again. Again the if loop explained above is executed. This will continue untill the intervalCount becomes 0.

else {
clearTimeout(timer);
intervalCount = intervalCount ? intervalCount - 1 : 0;
if (intervalCount) {
    i = 0;
    timer = setTimeout(function() {
    $(".typed-letter").empty();
    typeSetting(intervalCount);
    }, 300);
}
}

For more realistic typing effect, we can add a blinking animation to the |.

.blinking{
    animation:blinkingText 1.2s infinite;
}
@keyframes blinkingText{
    0%{     color: #000;    }
    49%{    color: #000; }
    60%{    color: transparent; }
    99%{    color:transparent;  }
    100%{   color: #000;    }
}

const content = 'Code Review';
const speed = 100;
var i = 0;
var timer = 0;
var intervalCount = 0;

function typeSetting(interval) {
  let el = $('#bar');
  if (interval) intervalCount = interval;
  if (i < content.length) {
    el.before(`<span class='typed-letter'>${content[i]}</span>`);
    i++;
    timer = setTimeout(function() {
      typeSetting(intervalCount)
    }, speed);
  } else {
    clearTimeout(timer);
    intervalCount = intervalCount ? intervalCount - 1 : 0;
    if (intervalCount) {
      i = 0;
      timer = setTimeout(function() {
        $(".typed-letter").empty();
        typeSetting(intervalCount);
      }, 300);
    }
  }
}

(function() {
  typeSetting(2); // may be you are using some kind of repetition count, set the count. If no params then will show 1 time.
})();
p {
  line-height: 10px;
}
.blinking{
    animation:blinkingText 1.2s infinite;
}
@keyframes blinkingText{
    0%{     color: #000;    }
    49%{    color: #000; }
    60%{    color: transparent; }
    99%{    color:transparent;  }
    100%{   color: #000;    }
}

 |

Here no external packages are used, no libraries. Its pure javascript.


Hash password and verify password with Node's Crypto

Glad to see you are using an adaptive encryption approach in PBKDF2.

You might consider Argon2 library as a more specific use password encryption tool as Argon2 is now the OWASP-recommended password encryption algorithm for new implementations.

Even though you are using an adaptive encryption approach, you are not really doing anything to facilitate the "adaptive" part.  Let's say this code has been working in an application for a year or two and you decide at some point that you want to increase your number of iterations from 10K to 20K, or change the underlying encryption algorithm, or any of the other settings. What happens when you verify a password against a hash made using old settings?

Your code, as shown, could still handle the verification part in that the hash contains all the needed information for re-hashing the password being verified. This is a very common and reasonable way to be able to perform password verification.  However, a password verification event is the only opportunity you have to update the stored hash to a new hash based on new default settings.  As such, you may consider being able to trigger an update of the password hash to a new hash if the current hash settings are different than the ones for the stored hash that is being used for verification.

Of course this logic doesn't need to exist in this specific module (it could exist outside this module higher up in application call stack), but it might mean that the verifyPassword() function might need to be aware of current settings and trigger a callback to update password hash, or change the return such that caller gets indication that there is need to update hash upon successful verification of password in old hash format.

Based on above comments, you might consider deriving your default password encryption settings from configuration rather than having them hard-coded in your module.

You may consider adding the ability to log out hash creation timings so as to allow you to more easily tune the work factor value to meet appropriate use case for your application (i.e. say you wanted the hashing process to take 1 second, you could tune the rounds value to achieve that approximate completion time for you application and environment).  This is another reason why you should probably store hash settings in config, to make it easier to tune the encryption for your application without having to actually change your code.


Optimizing Floodfill algorithm implementation as much as possible

Monitor.IsEntered

This call basically makes no sense. Monitor.IsEntered is used for coordination/mutual exclusion between threads. There are no threads here, and even if there were, there is no reason to lock on i: it is a counter. It isn't even a meaningful target for Monitor.IsEntered because it isn't an object.

There is no apparently threading going on here, so you can confidently remove all the locking stuff (including Interlocked.Increment). This may noticeably improve performance, since Monitor.IsEntered is non-trivial, and the call will incur boxing (so at worse this will improve the memory characteristics of your code).

If, for some reason, you are reading i from a different thread while the flood-fill is running, then you might want to use Interlocked methods to provide some notion of up-to-dateness.... but unless you are using that low-latency synchronisation (in which case it is a bad choice for doing so) you won't in practice need any manual memory barriers here. If it is not the case that you want to access i before this has finished then keep track of it as a 'normal' variable, and then set it as out at the end (if it is needed at all). out parameters can be abused, and may interfere with the compilers ability to perform optimisations.

100000

What is this?

if (i > 100000)
    break;

This is a magic number threshold. This says "if I happen to look at some mysterious number of entries, then I will give up and provide a mangled result". This is terrible, especially so because it isn't documented. If you want a cut-out, then have the threshold passed as a parameter, and document it in the inline documentation. It's good that you have inline documentation, but it isn't very helpful at the moment, failing to explain what any of the parameters are beyond suggesting that target will be 'replaced' (what does that mean?).

Furthermore, if it does cut out, then the consumer should be informed. You could throw a FloodfillCutoffException, or return a bool indicating that it did not complete, or something else.

HashSet/Stack

You should probably be using a Stack. HashSet.Contain is efficient (for what it does), but you don't need it. (This is assuming that target.Equals(replacement) is always false, but if that isn't the case then your code is broken anyway, because it doesn't keep track of pixels it has dequeued)

Excepting the first pixel, if you set source[targetIndex] = replacement when you queue it then you don't need to check if it is already in the HashSet: you only need to check that source[targetIndex].Equals(target), which you have to do anyway. The probably with your non-HashSet code wasn't the Stack, it was how you were using it.

With a stack, the code will look mostly the same, only you'll be Poping from the stack (instead of using First() and Remove(T). It should be much faster, because it doesn't lean on HashSet, which while being 'kind of O(1)' isn't going to outperform a single array lookup which probably needs to be done anyway.

Indexing

I'm guessing Pn is static, and looks something like this:

static int Pn(int x, int y, int width => x + y * width;

IEquatable<T>

It's good that you are using this.

Naming

Most of the names are cryptic. This is not ideal. It isn't clear why you use P rather than Pn. i and _i are completely unrelated (and both poor names). target and targetIndex are mostly unrelated.

Code

Here is a (completely untested) rework of your code I threw together in a hurry incorporating some of the points above, with some added comments.

public static void FloodFill<T>(this T[] source, int x, int y, int width, int height, T target, T replacement, int cutoff, out int explored)
    where T : IEquatable<T>
{
    // code can't handle this, so throw
    if (target.Equals(replacement))
    {
        throw new ArgumentException("Target and Replacement cannot equate");
    }

    // do start manually, and exit quickly if appropriate
    int start = P(x, y, width, height);
    if (!source[start].Equals(target))
    {
        explored = 0;
        return;
    }

    // stack is not a great name, but I'm in a hurry right now...
    Stack<int> stack = new Stack<int>();
    stack.Push(start);

    int count = 1;
    while (queue.Count > 0)
    {
        int _i = stack.Pop(),
            _x = _i % width,
            _y = _i / width;

        for (int offsetX = -1; offsetX < 2; offsetX++)
            for (int offsetY = -1; offsetY < 2; offsetY++)
            {
                // do not check origin or diagonal neighbours
                if (offsetX == 0 && offsetY == 0 || offsetX == offsetY || offsetX == -offsetY || -offsetX == offsetY)
                    continue;

                int targetIndex = Pn(_x + offsetX, _y + offsetY, width); // This is already inverted that's why we don't use F.P(...)
                int _tx = targetIndex % width,
                    _ty = targetIndex / width;

                // skip out of bounds point
                if (_tx < 0 || _ty < 0 || _tx >= width || _ty >= height)
                    continue;

                // if pixel matched target, reset it and queue
                if (source[targetIndex].Equals(target))
                {
                    source[targetIndex] = replacement;

                    stack.Push(targetIndex);
                    count++;
                }
            }

        if (i > cutoff)
            throw new Exception("FloodFill passed cutoff");
    }

    // report the number of cells explored
    explored = count;
}


How is OOP achieved with configuration files in PHP?

I personally use defines for for settings rather than utilising arrays.

A singleton is the correct route to go down and to help reduce your code and array you may want to use external files.

This is my config loader class with some simple caching that supports both database and file;

<?php
/**
 * Config loader
 */
final class Config extends Singleton{
    public static $loadedConfigs = array();

    /**
     * Get specific config value
     *
     * @param String $scope  Configuration scope, used to determine config location
     * @param String $module Specific config module name
     * @param String $param  (optional) Specific config option
     *
     * @return Mixed    Requested parameter value if requested, otherwise associative array or configuration key:pair values unless config file couldn't be loaded, then false
     * @author Dean Whitehouse
     * @copyright Dean Whitehouse 2014
     * @todo verify the config name is a valid one
     */
    public static function get($scope, $module, $param = null){
        if($param !== null && $param != ''){
            $const = strtoupper((string)$param);
        }

        $errorAppend = '; requested scope `'.$scope.'` with module `'.$module.'`;'.($param !== null ? 'Parameter requested `'.$param.'`' : '');

        if(isset(static::$loadedConfigs[$scope][$module])){
            $config = static::$loadedConfigs[$scope][$module];

            if(isset($const)){
                if(!isset($config[$const])){
                    error_log('Constant `'.$const.'` undefined'.$errorAppend);
                    return false;
                }
                else
                    $config = $config[$const];
            }
            return $config;
        }
        else{
            if($scope == 'core'){
                $file = '_app/core/config/'.$module.'.config.php';

                if(!file_exists($file)){
                    error_log('Config file doesn\'t exist at `'.$file.'`'.$errorAppend);
                    return false;
                }
                else{
                    $consts = get_defined_constants(true);
                    $consts = isset($consts['user']) ? $consts['user'] : array();

                    require_once $file;

                    $new = get_defined_constants(true);
                    $new = $new['user'];
                    $diff = array_diff_assoc($new, $consts);
                    static::$loadedConfigs[$scope][$module] = $diff;

                    if(isset($const)){
                        if(defined($const))
                            return constant($const);
                        else{
                            error_log('Constant `'.$const.'` undefined'.$errorAppend);
                            return false;
                        }
                    }

                    return static::$loadedConfigs[$scope][$module];
                }
            }
            elseif($scope == 'coreDB'){
                $check = db\sqli::query("SHOW TABLES LIKE '".db\sqli::escape($module)."'; -- Database check");

                if($check->num_rows == 0){
                    error_log('Config table doesn\'t exist'.$errorAppend);
                    return false;
                }
                else{
                    $query = 'SELECT `key`, `value` FROM `'.db\sqli::escape($module).'`';
                    if($param !== null){
                        $query .= ' WHERE `key` = '.db\sqli::escape($param).' LIMIT 1';
                    }

                    $query = db\sqli::query($query);

                    if($query->num_rows > 0){

                        $consts = get_defined_constants(true);
                        $consts = isset($consts['user']) ? $consts['user'] : array();

                        while($config = $query->fetch_assoc()){
                            define($config['key'], $config['value']);
                        }

                        $new = get_defined_constants(true);
                        $new = $new['user'];
                        $diff = array_diff_assoc($new, $consts);
                        static::$loadedConfigs[$scope][$module] = $diff;

                        if(isset($const)){
                            if(defined($const))
                                return constant($const);
                        }

                        return static::$loadedConfigs[$scope][$module];
                    }
                    else{
                        error_log('Constant `'.$const.'` undefined'.$errorAppend);
                        return false;
                    }

                }
            }
            else{
                error_log('Config scope `'.$scope.'` isn\'t recognised'.$errorAppend);
                return false;
            }
        }
    }

    /**
     * Load configuration module
     *
     * @param String $scope  Configuration scope, used to determine config location
     * @param String $module Specific config module name
     *
     * @return Mixed    False if configuration couldn't be loaded, otherwise associative array or configuration key:pair values
     * @author Dean Whitehouse
     * @copyright Dean Whitehouse 2014
     */
    public static function load($scope, $module){
        return static::get($scope, $module);
    }
}
?>

I call it like:

Config::load('core', 'env');
Config::load('core', 'db');

Edit

Sample config file 'env.config.php'

<?php
define('AUTO_REPAIR', true);

define('APP_ROOT', rtrim($_SERVER['SCRIPT_NAME'], '/index.php')); //folder the root of the site is in - only if in a directory

define('SECURE', true);

define('LOG_DIR', '_app/logs/');

define('SECURE_KEY', ''); //used for CSRF, NONCE and Cookies
?>


Finding world-writable files in local directories only

Processing mount points

This can be improved in many ways:

# Compile a list of mountpoints that need to be scanned
my @mounts;
open MT, "<${MTAB}" or die "Cannot open ${MTAB}, $!";

# We only want the local mountpoints
while (<MT>) {
  if ($_ =~ /ext[34]/) {
    my @line = split;
    push(@mounts, $line[1]);
  }
}

close MT;

Using bare names for file handles is not recommended:
replace MT with my $MT, and <MT> with <$MT>.

The comment talks about local mount points.
That's too vague, when in fact you're looking specifically for ext3 and ext4 filesystems.

You could simplify if ($_ =~ /ext[34]/) as if (/ext[34]/).

You could put the entire while loop inside a map, and it will be still readable.

Putting it together, you can rewrite like this:

open my $MT, "<${MTAB}" or die "Cannot open ${MTAB}, $!";

# Compile a list of mountpoints that need to be scanned
# We only want the ext3 ext4 partitions
my @mounts = map((split)[1], grep(/ext[34]/, <$MT>));

close $MT;

Note that if you didn't find any mount points,
the script has nothing to process, so it should exit:

die 'no mount points to process' unless @mounts;

Try to apply these techniques everywhere in the script,
especially the bit about filehandlers.

# Read in the list of excluded files and create a regex from them
my $regExcld = do {
  open XCLD, "<${EXCLUDE}" or die "Cannot open ${EXCLUDE}, $!\n";
  my @ignore = <XCLD>;
  chomp @ignore;
  local $" = '|';
  qr/@ignore/;
};

As earlier, replace XCLD with my $XCLD or something.
You also forgot to close it.

Btw, a common way to shorten my @arr = <$fh>; chomp @arr as chomp(my @arr = <$fh>).

Most importantly,
should it be really a fatal error if the file with excluded patterns doesn't exist?
It might make sense to make this optional.
Perhaps issue a warning instead, something like this:

my $regExcld = do {
  if (open my $fh, "<${EXCLUDE}") {
      chomp(my @ignore = <$fh>);
      close($fh);
      local $" = '|';
      qr/@ignore/;
  } else {
      warn "Cannot open ${EXCLUDE}, $!\n";
      undef;
  }
};

This bit seems pointless:

# Create a regex containing mountpoint dev numbers to compare file device numbers to.
my $devRegex = do {
  chomp @devNum;
  local $" = '|';
  qr/@devNum/;
};

Because @devNum is an empty array in your script,
you never actually gave it any values.

This is quite strange:

# Create the output file path if it doesn't already exist.
mkdir("${DIR}" or die "Cannot execute mkdir on ${DIR}, $!") unless (-d "${DIR}");

You misplaced the die:
it will run if "${DIR}" is empty,
not if mkdir fails.

Also, there's no need whatsoever to double-quote ${DIR}.

Corrected and simplified:

mkdir($DIR) or die "Cannot execute mkdir on ${DIR}, $!" unless -d $DIR;


Instead of magic constants like "N", "S" etc. use an enum which contains named constants and their values are checked on compile time.

public enum Orientation {
  NORTH, SOUTH, WEST, EAST
}

With plain Strings it's too easy to set an invalid value to the orientation field.
You can move the turnClockwise method to an enum:

public enum Orientation {
  NORTH {
    @Override
    public Orientation turnClockwise() {
      return EAST;
    }
  },
  SOUTH {
    @Override
    public Orientation turnClockwise() {
      return WEST;
    }
  },
  WEST {
    @Override
    public Orientation turnClockwise() {
      return NORTH;
    }
  },
  EAST {
    @Override
    public Orientation turnClockwise() {
      return SOUTH;
    }
  };

  public abstract Orientation turnClockwise();

}

It increases cohesion and replaces conditional with polymorphism.

(I'd also try to create a Position class with x and y coordinates and move the statements from the moveForwards method to this class like goNorth(), goWest() etc. Then a new Position moveForward(Position current) method in the Orientation enum would call one of the Position.go*() methods.)
I'd change this array:

position = new int[] {0, 0};

to two ints:

private int positionX;
private int positionY;

Indexes here (0 and 1) are magic constants.
The moveForwards and the the Tractor class looks unfinished. Noone writes the field array.
This:

try {
  throw new TractorInDitchException();
} catch (final TractorInDitchException e) {
  e.printStackTrace();
}

could be written as

new TractorInDitchException().printStackTrace();

without the try-catch structure. A logger framework (for example SLFJ and Logback) would be better here.
What should happen when the tractor reach the border of the field? (When the index is negative or greater than or equal to the size of the array.)


Here's my final implementation with the changes based on @Robert Snyder's comment:

  My first suggestion is to make refactor a little bit your constructor.
  Start by making a Method getCipherInstance() put your try catches in
  that method. Then make another method initializeCipher() This will
  make your constructor easier to read. As for your random IV generator
  you might want to consider a lesson from how Mifare Desfire passes
  enciphered data. You basically start with a IV of 0x00 and have a key
  that is known elsewhere. In the end hacking is much more difficult.

import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class Encrypt {

    private Cipher encryptCipher;
    private SecretKey key;
    private IvParameterSpec iv;

    private byte[] clearText;
    private byte[] encryptedText;

    /**
     * Encrypts data using AES-128
     * @param clearText The data to be encrypted
     */
    public Encrypt(String clearText) {

        //Generate the IV and key
        this.iv = new IvParameterSpec(this.generateIv());
        this.key = this.generateKey();
        this.encryptCipher = createCipher();
        this.clearText = this.convertClearText(clearText);
        this.encryptedText = this.encrypt();
    }

    /**
     * Converts the clear text passed by the user to an array of bytes
     * @param clearText The clear text passed by the user
     * @return The byte representation of the clear text
     */
    private byte[] convertClearText(String clearText) {

        //Convert the clear text passed by the user into bytes
        try {
            return clearText.getBytes("UTF-8");
        }
        catch(UnsupportedEncodingException ex) {
            Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * Creates an AES cipher using CBC mode with PKCS5 padding
     * @return The cipher used to encrypt data
     */
    private Cipher createCipher() {

        //Create an AES cipher in CBC mode using PKCS5 padding
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, this.key, this.iv);
            return cipher;
        }
        catch(NoSuchAlgorithmException ex) {
            Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        catch(NoSuchPaddingException ex) {
            Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        catch(InvalidKeyException ex) {
            Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        catch(InvalidAlgorithmParameterException ex) {
            Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * Generates a random IV to be used in the encryption process
     * @return The IV's byte representation
     */
    private byte[] generateIv() {
        SecureRandom random = new SecureRandom();
        byte[] ivBytes = new byte[16];
        random.nextBytes(ivBytes);
        return ivBytes;
    }

    /**
     * Generates a secret key to be used in the encryption process
     * @return The secret key
     */
    private SecretKey generateKey() {
        KeyGenerator keygen;
        try {

            //Java normally doesn't support 256-bit key sizes without an extra installation so stick with a 128-bit key
            keygen = KeyGenerator.getInstance("AES");
            keygen.init(128);
            SecretKey aesKey = keygen.generateKey();
            return aesKey;
        }
        catch(NoSuchAlgorithmException ex) {
            Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * Returns the initialization vector
     * @return The randomly generated IV
     */
    public IvParameterSpec getIv() {
        return this.iv;
    }

    /**
     * Returns the key used for encryption
     * @return The randomly generated secret key
     */
    public SecretKey getKey() {
        return this.key;
    }

    /**
     * Encrypts the data passed during instantiation of this object
     * @return The byte representation of the encrypted data
     */
    public final byte[] encrypt() {
        try {
            return this.encryptCipher.doFinal(this.clearText);
        }
        catch(IllegalBlockSizeException ex) {
            Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        catch(BadPaddingException ex) {
            Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * Returns the encrypted text as a base64 encoded string
     * @return The encrypted base64 encoded string
     */
    @Override
    public String toString() {
        return Base64.encode(encryptedText);
    }

}

Here is the most recent version of the class. One of the suggestions was to set the IV to 0x00 which I did not do. Someone correct me if I'm wrong but I'm almost positive that it is critical to have random data for the IV for each encryption operation. I've done what others have suggested and bubbled the exceptions up. The constructor has also been cleaned up quite a bit and there's now a toString() method that returns the data as a base64 encoded string.

import org.apache.commons.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public final class Encrypt {

    private Cipher encryptCipher;
    private SecretKey key;
    private IvParameterSpec iv;

    private byte[] clearText;
    private byte[] encryptedText;

    /**
     * Encrypts data using AES-128
     *
     * @param clearText The data to be encrypted
     * @throws java.security.NoSuchAlgorithmException
     * @throws javax.crypto.NoSuchPaddingException
     * @throws java.security.InvalidKeyException
     * @throws javax.crypto.BadPaddingException
     * @throws java.security.InvalidAlgorithmParameterException
     * @throws javax.crypto.IllegalBlockSizeException
     * @throws java.io.UnsupportedEncodingException
     */
    public Encrypt(String clearText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {

        //Generate the IV and key
        this.iv = new IvParameterSpec(this.generateIv());
        this.key = this.generateKey();
        this.encryptCipher = createCipher();
        this.clearText = this.convertClearText(clearText);
        this.encryptedText = this.encrypt();
    }

    /**
     * Converts the clear text passed by the user to an array of bytes
     *
     * @param clearText The clear text passed by the user
     * @return The byte representation of the clear text
     */
    private byte[] convertClearText(String clearText) throws UnsupportedEncodingException {

        //Convert the clear text passed by the user into bytes
        return clearText.getBytes("UTF-8");
    }

    /**
     * Creates an AES cipher using CBC mode with PKCS5 padding
     *
     * @return The cipher used to encrypt data
     */
    private Cipher createCipher() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {

        //Create an AES cipher in CBC mode using PKCS5 padding
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, this.key, this.iv);
        return cipher;
    }

    /**
     * Generates a random IV to be used in the encryption process
     *
     * @return The IV's byte representation
     */
    private byte[] generateIv() {
        SecureRandom random = new SecureRandom();
        byte[] ivBytes = new byte[16];
        random.nextBytes(ivBytes);
        return ivBytes;
    }

    /**
     * Generates a secret key to be used in the encryption process
     *
     * @return The secret key
     */
    private SecretKey generateKey() throws NoSuchAlgorithmException {
        KeyGenerator keygen;

        //Java normally doesn't support 256-bit key sizes without an extra installation so stick with a 128-bit key
        keygen = KeyGenerator.getInstance("AES");
        keygen.init(128);
        SecretKey aesKey = keygen.generateKey();
        return aesKey;

    }

    /**
     * Returns the initialization vector
     *
     * @return The randomly generated IV
     */
    public IvParameterSpec getIv() {
        return this.iv;
    }

    /**
     * Returns the key used for encryption
     *
     * @return The randomly generated secret key
     */
    public SecretKey getKey() {
        return this.key;
    }

    /**
     * Encrypts the data passed during instantiation of this object
     *
     * @return The byte representation of the encrypted data
     */
    private byte[] encrypt() throws IllegalBlockSizeException, BadPaddingException {
        return this.encryptCipher.doFinal(this.clearText);

    }

    /**
     * Returns the encrypted text as a base64 encoded string
     *
     * @return The encrypted base64 encoded string
     */
    @Override
    public String toString() {
        return Base64.encodeBase64String(encryptedText);
    }

}


Batch Insert Figures Into Powerpoint Slides with VBA

Overall, there's not much to comment on for the code logic -- it does what you need it to do. But there are some details to pay attention to that will help in this and future code.

Always use Option Explicit. There are a couple of undeclared variables/objects in your code that leads me to believe this directive is not present. Turn it on and leave it on.
Be careful when declaring multiple variables on a single line.

In your code where you have
Dim StartNum, EndNum As Integer

Then StartNum will be a Variant and EndNum will be an Integer, which is not exactly what you want. It might be a pain, but save yourself and declare each variable on a separate line (once it's a habit, it's not as bad as you think).

Declare your number variables as Long, not Integer. This answer gives a very detailed explanation, but just know it's considered a "best practice" to always use Long.
This point is more of a stylistic convention, but it's considered "standard" (personal preferences apply) to declare variables with camelCase and procedure names with PascalCase and constants with SHOUTY_SNAKE_CASE (reference). If you read that reference, PLEASE don't fall down the Hungarian case rabbit hole. (These conventions can lead to highly entertaining comments and emotional battles about the merits of these conventions. Do what I do:  get some popcorn and enjoy the show ;) )
Pay attention to the arguments in your functions or subs and identify each parameters as ByRef or ByVal. Microsoft explains the difference (using Visual Basic, but it's essentially the same in VBA), and there are other good references to read to learn more about it.
This is really my own personal preference, but I do try to limit the line length of each statement to around 80 characters. It it's longer, I add the continuation character. This is more of a guideline than a hard rule (for me), but it does make code easier to read.

The example below is my implementation of your code, as modified by my comments.
Option Explicit

Sub InsertFigures()
    'Reference: (Show object name) https://stackoverflow.com/a/52088805
    'Reference: (Replace image) https://stackoverflow.com/a/18083223

    Dim baseSlideNumber As Long
    Dim startNum As Long
    Dim endNum As Long
    startNum = 1
    endNum = 30
    baseSlideNumber = 2

    Dim loopNumber As Long
    Dim newSlide As SlideRange
    For loopNumber = startNum To endNum
      Set newSlide = ActivePresentation.Slides(baseSlideNumber).Duplicate
    Next loopNumber

    For loopNumber = startNum To endNum
        Dim newPictureFilename As String
        Dim targetSlideNumber As Long
        newPictureFilename = "F:\Images\" & CStr(loopNumber) & ".bmp"  ' Source Image Path
        targetSlideNumber = baseSlideNumber + (loopNumber - startNum + 1)

        Dim topProperty As Double
        Dim leftProperty As Double
        Dim heightProperty As Double
        Dim widthProperty As Double
        Dim softEdgeProperty As Double

        'Capture properties of exisitng picture such as location and size
        Dim objectForGettingProperties As Shape
        Set objectForGettingProperties = GetShapeByName("Image1", targetSlideNumber)
        With objectForGettingProperties
            topProperty = .Top
            leftProperty = .Left
            heightProperty = .Height
            widthProperty = .Width
            'SoftEdgeProperty = .SoftEdge
        End With
        objectForGettingProperties.Delete           ' Delete origin placeholder

        Dim newImageObject As Object
        Set newImageObject = ActivePresentation.Slides(targetSlideNumber) _
                                     .Shapes.AddPicture(newPictureFilename, _
                                                        msoFalse, msoTrue, _
                                                        leftProperty, _
                                                        topProperty, _
                                                        widthProperty, _
                                                        heightProperty)
        newImageObject.Name = "NewImage"        'Set image name
        newImageObject.SoftEdge.Radius = 8.86
    Next loopNumber
End Sub

Function GetShapeByName(ByVal shapeName As String, ByVal Slide As Long) As Shape
    'Reference: https://stackoverflow.com/a/5527604
    Set GetShapeByName = ActivePresentation.Slides(Slide).Shapes(shapeName)
End Function


Effective & Secure Method to populate Access Token for authorization header in Rest Template

You can have an interceptor on RestTemplate. It will be called for each request. You can have the access token logic within the interceptor. You can also implementing caching so that you do not fire two requests for each task. In case the token expires (401 response), you can regenerate the token

@Component
class MyInterceptor implements ClientHttpRequestInterceptor {
   @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution){
      HttpHeaders headers = request.getHeaders();
      headers.setBearerAuth(someCachedService.getBearerToken());
      ... response = execution.execute(request, body);
     // handle unauthorized request

   }
}

@Bean
RestTemplate restTemplate(MyInterceptor interceptor){
  RestTemplate restTemplate = new RestTemplate();
  restTemplate.setInterceptors(Arrays.asList(interceptor));
}


Firstly, modify or return, don't do both.

Your process method returns lists as well as modify them. Either you should construct a new list and return that, or modify the existing list and return nothing.

Your remove_overlap function does the same thing. It should either modify the incoming list, or return a new list not both.

You index [0] and [1] on the tuples a lot to fetch the start and end. That's best avoided because its not easy to tell whats going on.

rs[start-1] = ((rs[start][0],rs[start-1][0])[rs[start-1][0] < rs[start][0]],(rs[start][1],rs[start-1][1])[rs[start-1][1] > rs[start][1]])

Ouch! That'd be much better off broken into several lines. You shouldn't need to check which of the starts is lower because sorting the array should mean that the earlier one is always lower. I'd also use the max function to select the larger item, (if you don't  have it in your version of python, I'd just define it)

Your loop is backwards, working from the end. That complicates the code and makes it harder to follow. I'd suggest reworking it work from the front.

return process(rs,0)

You start the checking process over again whenever you merge two ranges. But that's not so great because you'll end up rechecking all the segments over and over again. Since you've already verified them you shouldn't check them again.

Your recursion process can be easily rewritten as a while loop. All you're doing is moving an index forward, and you don't really need recursion.

This is my implementation:

def remove_overlap(ranges):
    result = []
    current_start = -1
    current_stop = -1

    for start, stop in sorted(ranges):
        if start > current_stop:
            # this segment starts after the last segment stops
            # just add a new segment
            result.append( (start, stop) )
            current_start, current_stop = start, stop
        else:
            # segments overlap, replace
            result[-1] = (current_start, stop)
            # current_start already guaranteed to be lower
            current_stop = max(current_stop, stop)

    return result


Merge Two Sorted Lists by splicing together the nodes of the first two lists

LGTM.

Still a couple of notes:

A null in a conditional context evaluates to false. It is safe to omit an explicit comparison to null, along the lines of

    while (listNode1 && listNode2) {

Ditto for if (listNode1) and if (listNode2).
Mandatory stability loss notice. The if (listNode1.val < listNode2.val) test loses stability: when the values compare equal, an element from the second list is merged first.

The stability of merge is not required by the problem statement, and doesn't matter for integers. Just be aware.


Simplifying and optimizing factors and prime factorization generator

I have a couple of suggestions that you may wish to consider:

Don't return a string with the complete statement, return a std::vector/std::map instead with the values, and later assemble the string. It will keep the values in a more usable form and separate out the concerns. You're half doing this with findFactors, go all the way!
In findPrimeFactorization, your main loop has a terminating condition that varies both sides (i <= posInt), which is a little confusing to reason about. Instead, rewrite it to a while ( posInt != 1 ), which is your actual termination.
In findPrimeFactorization, to speed things up (slightly) you can try testing 2 separately, then 3, 5, 7... within the loop (other more complex shortcuts are available)
In terms of writing out the prime factors, you can combine the ideas behind the questions infix_iterator code and std::copy to std::cout for std::pair to get something that's nice, if a little obscure.


Your Items initialization I believe isn't threadsafe. Use Lazy<T> for thread safe lazy initialization instead.
The ReadOnlyCollection isn't thread safe.

A ReadOnlyCollection can support
multiple readers concurrently, as long
as the collection is not modified.
Even so, enumerating through a
collection is intrinsically not a
thread-safe procedure. To guarantee
thread safety during enumeration, you
can lock the collection during the
entire enumeration. To allow the
collection to be accessed by multiple
threads for reading and writing, you
must implement your own
synchronization.

Consider using a ReaderWriterLock to support a single writer, but multiple readers.

Furthermore, consider reading this reply, and the blog post mentioned there, which discusses why thread safe collections are so hard, and not necessarily useful.


Autowiring publishers/listeners with reflection in Unity Framework

typeof(IMessageListener<object>).GetGenericTypeDefinition()

You can simplify this to just:

typeof(IMessageListener<>)

Why are you combing Where() with an if? I would stick with one or the other.

interf.GetGenericArguments().FirstOrDefault()

Don't use OrDefault when you're not going to deal with the null. That way, when an error happens, you're going to get a descriptive exception right away, instead of a confusing NullReferenceException later.

If this is part of the exception handling that you removed, then that makes it hard to review your code properly.

// […] the array is ugly, but i just keep getting an error without it

You have to use an array here, MethodInfo.Invoke() is not a params method.


Amalgamation of the repository and command / query pattern

I'll address your separate classes for the queries first. I definitely see where you're coming from with this approach and I can dig it, but it gives too much duplication as it is.

I assume you'll have more entities than just Addresses so using your approach, you would have to create a new interface for each entity you want to get by its ID. If you instead added some generics, you can do all of this with one interface:

interface IGetEntityByIdQuery<T> {
    T execute(int id);
}

Now you can have these implementations:

class GetAddressByIdQuery : IGetEntityByIdQuery<Address> {
    Address execute(int id) { }
}

class GetOrderByIdQuery : IGetEntityByIdQuery<Order> {
    Order execute(int id) { }
}

However even though I first said I can dig it, this will still be very cumbersome to work with. Having to create a new class for the retrieval for each entity for each parameter? That's too much.

I can agree on a setup where you combine them by entity:

interface IGetEntity<T> {
    T GetEntityById(int id);
    T GetEntityByPersonId(int id);
}

Now on to your remark about CRUD:

  I have seen people use repositories for CRUD too but then I get the impression it is doing too much thus warrants further abstraction.

The entire idea behind repositories is CRUD. In fact, your GetXByY classes are simply executing the R part in CRUD. Repositories exist to provide communication from your model to your datasource, which is what we understand under CRUD.

Another red flag here should have been your name choice: when you have a class named XManager you have to really overthink your design and be sure that this is the way to go. Often it is an indication something is wrong because in essence, a "manager" class doesn't convey much meaning.

What does this class do? Other names for such encompassing classes are a lot more informative, for example XFactory indicates the class will construct instances of X. A manager.. manages?

Therefore these actions should be added to your repository. This will now keep these related actions (CRUD) together which prevents any confusion with other programmers.

That being said: it might very well be a suitable name for a class, this is definitely not a general rule. I have had to use XManager classes as well before, but this was more because I simply couldn't come up with a better one (and no, it wasn't a repository ;)).

For more reflection upon the subject, I suggest reading this post.

As for your final question on the topic of errors: why are you doing validation logic in your data access layer? That is way too late!

You should have the guarantee that when an object is constructed, it has valid data. The entire idea behind getters and setters (aka: properties) is that the actual data is hidden and that the data can be validated.

When you construct a new object of type Address, it should be validated. This can be done in several places: properties, constructor, the factory that creates Address objects using some service layer, etc. There are many options to do this validation, but once the object is constructed you should have the implicit guarantee that the object contains valid data.

Lastly, for the boundary checks (like id > 0): this is up to your own preference. You could add a service layer in front of your repository that validates the incoming data and if you have several validation requirements then this might be a good solution. If on the other hand you only have this one boundary check then it's a little minor.

But I haven't come across the explicit recommendation to use a service layer in front of your data access layer just for validation yet, so as far as I'm concerned this is up to yourself.


Recursive method turning flat structure to recursive

Below is the code for my approach.  A benefit is that the heirarchy goes both ways; up and down.  While the parent object contains a list of child objects, each child has a reference to the parent object.

Some differences from your original setup:

The ParentId property on FlatObject is nullable, so objects that have no parent will have null.
The Children property on RecursiveObject is IEnumerable instead of List.  This prevents consumers from modifying the contents of the list.  If you want to allow consumers to add/remove items from the list, then RecursiveObject should expose methods to perform those actions so that you can make sure that the Parent property is properly assigned when a child is added/removed.
I've made the Id, Parent, and Children properties on RecursiveObject read-only.  This certainly isn't necessary, but you can do that if desired.  This is the reason why I made the FlatObjectsToRecursiveObjects method as a static method of the RecursiveObjects class; so that it can have access to the private property setters.

The gist of this approach is that we first convert the FlatObjects to RecursiveObjects and store them in a dictionary keyed by the Id.  Then, we do another pass over the FlatObjects in order to assign the Parent and Children properties of each RecursiveObject, using the dictionary to perform the necessary look-ups with the FlatObject's Id and ParentId properties.

class FlatObject
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
}

class RecursiveObject
{
    public int Id { get; private set; }
    public RecursiveObject Parent { get; private set; }
    public IEnumerable<RecursiveObject> Children { get; private set; }

    public static IEnumerable<RecursiveObject> FlatObjectsToRecursiveObjects(IEnumerable<FlatObject> flatObjects)
    {
        // convert flat objects into heirarchial objects and store them in a dictionary keyed with the object's Id
        var recursiveObjectsById = flatObjects.Select(item => new RecursiveObject { Id = item.Id }).ToDictionary(item => item.Id);

        // group flat objects by their ParentId
        var flatObjectsGroupedByParentId = flatObjects.Where(item => item.ParentId.HasValue).GroupBy(item => item.ParentId.Value);
        foreach (var group in flatObjectsGroupedByParentId)
        {
            // find each group's parent object
            RecursiveObject parent;
            if (recursiveObjectsById.TryGetValue(group.Key, out parent))
            {
                // convert the group of flat objects to a list of heirarchial objects by looking up the correct heirarchial object from the dictionary
                parent.Children = group.Select(item => recursiveObjectsById[item.Id]).ToList();

                // assign the parent object to each child object
                foreach (var child in parent.Children)
                {
                    child.Parent = parent;
                }
            }
            else
            {
                // something's wrong!!!  ParentId refers to a non-existant object.
            }
        }

        return recursiveObjectsById.Values;
    }
}

EDIT:  Added an "improved" version of my original approach, shown below.  The following implementation provides the following benefits:

The Children property on RecursiveObject never returns a null, but it still retains the "benefit" of lazy initialization.  The Children property getter checks if the _Children field is null, and if so it returns the default instance of the EmptyEnumerable<RecursiveObject> class (code included).
Children can now be added/removed using the new AddChild, RemoveChild, and AddChildren methods on RecursiveObject.
The FlatObjectsToRecursiveObjects method is slightly simpler now because it utilizes the new AddChildren method.
The FlatObjectsToRecursiveObjects method no longer has to be a member of the RecursiveObject class, since it does not access any private details of the class.
My setup code includes a second root (new FlatObject(9,-1)) and circular references (new FlatObject(10,10) and new FlatObject(0,2)), just to verify that the implementation can handle these special cases.

class FlatObject
{
    public int Id { get; set; }
    public int? ParentId { get; set; }

    public FlatObject(int id)
    {
        this.Id = id;
    }

    public FlatObject(int id, int parentId)
        : this(id)
    {
        this.ParentId = parentId;
    }
}

class RecursiveObject
{
    public int Id { get; private set; }
    public RecursiveObject Parent { get; private set; }
    private List<RecursiveObject> _Children;

    public IEnumerable<RecursiveObject> Children
    {
        get
        {
            IEnumerable<RecursiveObject> value = _Children;
            if (value == null)
                value = EmptyEnumerable<RecursiveObject>.Default;
            return value;
        }
    }

    public RecursiveObject(int id)
    {
        this.Id = id;
    }

    public void AddChild(RecursiveObject child)
    {
        if (_Children == null)
            _Children = new List<RecursiveObject>();
        _Children.Add(child);
        child.Parent = this;
    }

    public bool RemoveChild(RecursiveObject child)
    {
        if (_Children != null)
        {
            bool removed = _Children.Remove(child);
            if (removed)
                child.Parent = null;
            return removed;
        }
        else
        {
            return false;
        }
    }

    public void AddChildren(IEnumerable<RecursiveObject> children)
    {
        if (children == null)
            throw new ArgumentNullException("children");

        if (_Children == null)
            _Children = new List<RecursiveObject>(children);
        else
            _Children.AddRange(children);

        foreach (var child in children)
        {
            child.Parent = this;
        }
    }
}

class Program
{
    public static IEnumerable<RecursiveObject> FlatObjectsToRecursiveObjects(IEnumerable<FlatObject> flatObjects)
    {
        // convert flat objects into heirarchial objects and store them in a dictionary keyed with the object's Id
        var recursiveObjectsById = flatObjects.Select(item => new RecursiveObject(item.Id)).ToDictionary(item => item.Id);

        // group flat objects by their ParentId
        var flatObjectsGroupedByParentId = flatObjects.Where(item => item.ParentId.HasValue).GroupBy(item => item.ParentId.Value);
        foreach (var group in flatObjectsGroupedByParentId)
        {
            // find each group's parent object
            RecursiveObject parent;
            if (recursiveObjectsById.TryGetValue(group.Key, out parent))
            {
                // convert the group of flat objects to a list of heirarchial objects by looking up the correct heirarchial object from the dictionary
                parent.AddChildren(group.Select(item => recursiveObjectsById[item.Id]));
            }
            else
            {
                // something's wrong!!!  ParentId refers to a non-existant object.
            }
        }

        return recursiveObjectsById.Values;
    }

    static void Main(string[] args)
    {
        List<FlatObject> flatObjects = new List<FlatObject>()
            {
                new FlatObject(1,0),
                new FlatObject(2,0),
                new FlatObject(3,0),
                new FlatObject(4,0),
                new FlatObject(5,1),
                new FlatObject(6,2),
                new FlatObject(7,6),
                new FlatObject(8,6),
                new FlatObject(9,-1),
                new FlatObject(10,10),
                new FlatObject(0,2),
            };

        var recursiveObjects = FlatObjectsToRecursiveObjects(flatObjects).ToList();
    }
}

#region Universal Code

class EmptyEnumerator<T> : IEnumerator<T>
{
    public static readonly EmptyEnumerator<T> Default = new EmptyEnumerator<T>();

    public T Current
    {
        get { throw new InvalidOperationException(); }
    }

    public void Dispose()
    {
    }

    object System.Collections.IEnumerator.Current
    {
        get { throw new InvalidOperationException(); }
    }

    public bool MoveNext()
    {
        return false;
    }

    public void Reset()
    {
    }
}

class EmptyEnumerable<T> : IEnumerable<T>
{
    public static readonly EmptyEnumerable<T> Default = new EmptyEnumerable<T>();

    public IEnumerator<T> GetEnumerator()
    {
        return EmptyEnumerator<T>.Default;
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

#endregion


Here's the code smells:

The new keyword in a class definition
A result() method and $output attribute for data created by single method
A very long, ambiguous method: run
Two mostly-different SQL statements separated by an if-else

And here's what I'd do to eliminate them:

Move the PDO object to a constructor argument (see below) so you're not violating the Law of Demeter (see #1 and 2 here)
Remove result() altogether and simply return the result from the method in which it's built.
Break this into smaller, more meaningful methods based on responsibility (see #4 below)
Create getMissionaryByArea() and getAllMissionaries() methods with optional parameters

Here's what my code might look like:

<?php

/**
 * This class name is ambiguous.
 * I'm not sure what it means, so I cannot suggest a better name.
 */
class comps {

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }

    public function getMissionariesByArea($area, $admin_id=false, $omit_missionary_id=false, $limit=100) {
        $sql = <<<'ENDSQL'
        SELECT m.*
        FROM missionarios m
        JOIN missionary_areas ma ON ma.missionary = m.mid
        WHERE ma.area_uid = :area
        AND ma.missionary_released = '0'
        LIMIT :limit
ENDSQL;
        $params = [
            'area' => $area,
            'limit' => $limit
        ];

        if ($omit_missionary_id) {
            $sql .= ' AND ma.missionary <> :omit_missionary_id';
            $params['omit_missionary_id'] = $omit_missionary_id;
        }

        if ($admin_id) {
            $sql .= ' AND m.admin = :admin_id';
            $params['admin_id'] = $admin_id;
        }

        $sth = $this->pdo->prepare($sql);
        $sth->execute($params);
        return $sth->fetchAll();
    }

    public function getAllMissionaries($admin_id=false, $limit=100) {
        $sql = 'SELECT * FROM missionarios';
        $params = ['limit' => $limit];

        if ($admin_id) {
            $sql .= ' AND admin = :admin_id';
            $params['admin_id'] = $admin_id;
        }

        $sth = $this->pdo->prepare($sql);
        $sth->execute($params);
        return $sth->fetchAll();
    }
}

I can revise if I've missed something in my refactoring.


Locking is advisory which mean unless syslog is also doing flock() before write (which is doubtful) your locking scheme will have no effect. Some operating systems like AIX do have manditory/enforced locking mechanisms but I don't believe they're standard at the filesystem level across any UNIX system.


Decoding data from a MIDI controller as eight buttons

Use a dict for lookups
When doing lookups, Python provides an associative array data structure called a dict.  Your stacked ifs can be cleanly written as a dict lookup like:
button_text = {
    ("B", "1", "6"): "Button1",
    ("B", "1", "7"): "Button2",
    ("B", "1", "8"): "Button3",
    ("B", "1", "9"): "Button4",
    ("B", "1", "A"): "Button5",
    ("B", "1", "B"): "Button6",
    ("B", "1", "C"): "Button7",
    ("B", "1", "D"): "Button8",
}

print(button_text[data[-8], data[-5], data[-4]])


Implement pattern match on FindUsersByName

List<Profile.Membership> recs = (List<Profile.Membership>)memberMapper.GetMembershipsByUsername(_memberUtil.GetApplicationId(), usernameToMatch, pageIndex, pageSize, out totalRecords);

I don't understand why is the cast needed here, GetMembershipsByUsername() doesn't sound like a method for which a cast would be necessary.

Also, I think you should consider using var here, especially if you're going to keep the cast, so the type of the variable is clear. (I would probably use var even without the cast, but that's more debatable.)

Exception e = CheckEventLog(ex, "FindUsersByName");
throw e;

I don't see any reason for the (not very well named) variable e here, just throw the exception directly:

throw CheckEventLog(ex, "FindUsersByName");

Also, I think the method name CheckEventLog() could be improved. It's not clear at all that it returns an Exception, or what that exception means.

return users;

I would move this before the end of the try. That way, it's clearer that the method either returns a meaningful result or throws an exception. (And if you changed that later by removing or limiting the throw, you would get a compile error, which I think is a plus.)

Also, doing this means you can move the declaration of the users variable into the try too.