Authenticate users based on both user role, and requested operation

If return true, else return false

if(lv > conf.roleEditor)
    return true;
else
    return false;

Before we delve into the contextual considerations, an if that returns true or false is always a redundant if. This can at all times be refactored to:

return lv > conf.roleEditor;

Performance

  I see that, if the url is "/RoleEditor" but the power level is too low, all other comparisons will be made. A fix for this would be changing all to this:

The first question is always "does this performance need to be optimized?" As these are simple value comparisons, the performance cost is likely negligible. Assuming this method isn't being called many thousands of times in a given page load.

When performance cost is negligible, favor readability over (irrelevant) optimizations. In that regard, you're free to not avoid the additional checks if it makes the code more readable and doesn't meaningfully impact performance.

That being said, the code can be improved here, which I will get to. The main takeaway here is that you are not forced to optimize it the way you currently wanted to if there is no proven performance issue.

Authentication vs authorization

As others have already remarked, you're dealing with authorization here, not authentication.

Authentication = Who is this? (it's Bob)
Authorization = Can Bob delete users? (yes)

Secure authorization

You are showing a javascript method. Presumably, this runs in the client's browser. By putting the logic in the browser, your users are able to find it and alter it if they so choose. This is a bad idea for security concerns.

It's not necessarily wrong to perform these checks client-side (e.g. for a fast response and thus good user experience) if they are also backed by server-side security checks (to ensure that users fiddling with the authorization logic client-side are unable to perform actions server-side).

Optimizing the algorithm

With all these sidenotes out of the way, we move on to the actual issue you were asking about, optimizing the ifs. Reading the code, there is a general pattern to be spotted:

if(url == "MyString" && lv > conf.MyStringMinimumLevel)

Sometimes there is more than one allowed string, so we'll account for that, but the repeating pattern is otherwise always the same. I'm going to refer to these two values as "names" and "levels" in the rest of the answer for brevity's sake.

This immediately opens the door to abstraction by mapping these names and levels. In fact, you've already sort of done this with all your conf.roleEditor, conf.queuedata, ... values. You just haven't done it reusably, which is forcing you to manually write all your if checks. If you write it reusable, you can reduce this to a very simple process:

Fetch the level based on the url name
Check if the given user level is greater than the fetched level

var mappings =
{
    {
        "level" : 1
        "names" : [ "RoleEditor", "SaveRoles" ]
    },
    {
        "level" : 2
        "names" : [ "WriteQueueData" ]
    }
};

function isAuthorized(url, lv) {

    var mapping = mappings.find(m => m.names.includes(url.trim('/'));

    return mapping !== undefined
           && lv > mapping.level;
}

To explain:

.find() gives us the first item which conforms to the selection logic (or undefined if no such item exists).
The selection logic (.includes()) checks if a mapping contains a name that matches the url parameter.
By using url.trim('/'), you omit the first and last character (the /) from the URL when it is a / (but will leave any other characters). This just makes it easier for use to not have to constantly put the / in the mapping names.
The !== undefined check ensures that we return false if no mapping exists for the current URL. Your intended behavior may be different here - adjust it as you see fit.

You'll probably want to store this mapping in your conf object, but I'll leave the finer points up to you. This is just a basic example of how you can reduce the method.

Edit: Sidenote

If the conf object should not be altered (for whatever reason), you can work around this by indirectly using the values in the mappings:

var mappings =
{
    {
        "level" : conf.roleEditor,
        "names" : [ "RoleEditor", "SaveRoles" ]
    },
    {
        "level" : conf.queuedata,
        "names" : [ "WriteQueueData" ]
    }
};

// The function is unchanged

This is less ideal (it's better to just change the conf object) but if you can't change it, you can at least still work around it.


simple "if"-less algebraic computation using CLOS

(defmethod evaluate ((node op-node))
  (apply (value node)
         (list (evaluate (left-node node))
               (evaluate (right-node node)))))

can be written:

(defmethod evaluate ((node op-node))
  (funcall (value node)
           (evaluate (left-node node))
           (evaluate (right-node node))))

For this example, instead of different subclasses for every binary operation, you could just use a binop class and instantiate it with the respective functions, since they share the same evaluate method, but that depends on what else you want do do with the nodes. (Maybe, for example, you want to have different print-object methods for each of them.)

(Also, using toplevel setfs on unestablished symbols is considered bad style, but I suppose this was just for testing and demonstration purposes. In real code, defparameter or defvar should be used.)


Manipulating arrays to extract unique objects and count occurrences

Responding to your questions

  “Is there a simpler, more semantic, faster, or otherwise better way than to use two nested map in step 1?”

While I like the benefits of functional approaches, they are often slower because of the extra function calls.

Steps 1 and 2 could be simplified by using two for...of loops (since ecmascript-6 features like const are also used). Also, instead of constructing a new object to return in the nested map callback, you can just return subCategory.key2 (though perhaps you simplified the data and the original data contains more properties that aren't needed in the end).

const arrOfObj = [];
for (let category of arr) {
    for (let subCategory of category.key1) {
        arrOfObj.push(subCategory.key2);
    }
}

This generally works faster, at least for the small dataset supplied - see this jsPerf test for comparison

  “I realise that step 3 is longer than it should be and there has to be a better way to do it. How can step 3 be improved?”

I was thinking of using JSON.stringify() to make an array of counts in step 1 and then use JSON.parse() in step 3 for lookups in constant time, but apparently that was slower, possibly because of the original data set which only has 1 collision. Maybe for a larger dataset that would be faster. See this jsPerf for a comparison.

const arr = [
    {key1: [{key2: {id: 1, name: 'a'}}]},
    {key1: [{key2: {id: 2, name: 'b'}}]},
    {key1: [{key2: {id: 2, name: 'b'}}, {key2: {id: 3, name: 'c'}}]}
];
const counts = {};
for (let category of arr) {
  for (let subCategory of category.key1) {
    const countKey = JSON.stringify(subCategory.key2)
    counts[countKey] = (counts[countKey] || 0) + 1;
  }
}
const dedupedArrWithCount = [];
for (let key in counts) {
  const obj = JSON.parse(key);
  dedupedArrWithCount.push(Object.assign(obj, {
    count: counts[key]
  }));
}
console.log(dedupedArrWithCount);

Other feedback

The variable l is declared without any keyword:

let dedupedArrWithCount = [];
l = arrOfObj.length;

Unless this code is wrapped in an IIFE, l becomes a global variable, which can lead to unintentional consequences if that name is used later. Read more about this topic in this post about global variables.  It is advisable to use const (or let if there was a need to re-assign it).

In that same vein, dedupedArrWithCount could be declared with the const keyword, since it is never re-assigned, just mutated using the push method.

One other thing I noticed is that

const arrOfObj = [].concat(...arrOfArrOfObj);

Is equivalent to

const flatArr = arrOfArrOfObj.flat();

Using .flat() appears to run faster in Firefox and Safari but not Chrome, at least when I ran this jsPerf.


I don't think that you need newLibrary and tryLoadLibrary. The names don't really make clear what the distinction is, and I can't imagine that you'd ever want to load a library but not know if it failed or not.

Also, instead of printing, I would throw an exception. That way, the calling code can handle the case (what if it's an irrelevant library? Now the user is still annoyed with a meaningless message; but what if it's a highly relevant library? Is a small message really enough?).

I would also get rid of the distinction between lName and lValue. If you follow conventions, they should be the same anyways. If they are not, it might get confusing, especially because it's not just this call, but also how they are stored in loadedLibrarys[$lName] = $lValue;,

I would also rename tryLoadLibrary to loadAdditionalLibrary. try is not really needed (we can assume that it will only try), and additional makes it more fitting with loadLibrarys. lName and lValue are also not all that clear; if I didn't read your code, I'd have no idea what l is, or what name and what a value is. libraryClassName and libraryFileName would be clearer (you can also skip the library part, as it's clear from context.

Finally, I would always check for directory traversal when including with a variable. It shouldn't really be necessary in this situation, but it's just good practice, and doesn't cost that much.


Your sum(...) function is fine, given the specification, but there is jut an issue of input validation... what about negative values?

Your current loop condition is input >= 1. This would be better written as input > 0. When you see the >= 1 it makes you wonder if there's a condition that's weird. In this case, there's not.

Further, your code excludes all negative values. What about the sum of -123?

That makes me think that the code should all be looped on the condition input != 0, but that would sum -123 as -6, and not 6.

I was initially tempted to suggest that you have the code:

    input = Math.abs(input);

    int sum = 0;

    while ( input != 0 ) {
        sum += input % 10;
        input = input / 10;
    }

    return sum;

Unfortunately, that has a flaw with Integer.MIN_VALUE (the abs of Integer.MIN_VALUE is.... Integer.MIN_VALUE - a negative number). The net result, is that I considered doing an abs on each digit value inside the loop, but then realized, that all the digits will be negative, so the 'sum' will just be a large negative value, and we can take the absolute of the sum safely, because the sum of the digits will never be large enough to be a problem...

Thus, the solution I would recommend is:

public static int sumSumAbs(int input) {

    int sum = 0;

    while ( input != 0 ) {
        sum += input % 10;
        input = input / 10;
    }

    return Math.abs(sum);
}

That code (adjusted to fit in to my Eclipse IDE with a static method call, and different name), will work for any input value, of any sign, and ignore the sign in the result.


Checking whether a string ends with one of a list of suffixes

Yes, there is! Generator comprehensions and the any function to the rescue.

def checkEnds(line, ends):
    return any(line.endswith(end) for end in ends)

Just like the original code, this only checks as many line.endswith(end) as necessary, returning True on the first True result.


Setting and clearing setTimeout() inside of an event handler

Since you mention useReducer React hook I will assume you are using a functional component and thus can use other React hooks.
I suggest:

Use a React ref to hold a reference to the timer (versus global variable).
Use an useEffect hook to clear any running timeouts in the case the component unmounts before the timeout expires. Provide an empty dependency array so the effect callback is called only once. Here it is just to return the cleanup function to clear any running timeouts.

Code:
import { useEffect, useRef } from 'react';

...

// in component
const timerRef = useRef(null);

useEffect(() => {
  return () => clearTimeout(timerRef.current);
}, []);

const handler = (event, type) => {
  clearTimeout(timerRef.current);

  if (type === 'CHANGE') {
    timerRef.current = setTimeout(callback, 500, { argumentsForTheCallBack });
  }
}

Why provide cleanup function from useEffect?
If you attempt to update state of an unmounted component you'll get a React warning stating:

Warning: Can’t perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect
cleanup function.

It's just a warning though, so if you are ok with the warning in non-production builds and you know you don't actually have a memory leak (open sockets, connections, subscriptions, etc...) then you can likely safely ignore them.
In general you should strive to write code that doesn't generate warnings though, and this is a warning that is easily preventable.


It appears that if have access to the standard library version of snprintf you can do this:

char* FormatDate(DT dateTime)
{
      size_t needed = snprintf(NULL, 0,"%d,%d,%d,%d,%d,%d", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);
      char* formattedDate = (char*)malloc(needed);
      snprintf(formattedDate, needed,"%d,%d,%d,%d,%d,%d", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);
      return formattedDate;
}

Original source obtained from StackOverflow

char* get_error_message(char const *msg) {
    size_t needed = snprintf(NULL, 0, "%s: %s (%d)", msg, strerror(errno), errno);
    char  *buffer = malloc(needed);
    snprintf(buffer, needed, "%s: %s (%d)", msg, strerror(errno), errno);
    return buffer;
}

Copied from https://stackoverflow.com/questions/1775403/using-snprintf-to-avoid-buffer-overruns but duplicated to make finding answers quicker.


Plugin for WordPress and Foundation Reveal

L15, L26, L31-60: Inconsistent indentation levels.
L4-43: Consider indenting this block.
L04: I don't see the point in storing the ID rather than the jQuery object itself. Instead of var id = "#" + post_id;, go ahead and store the object: var $id = $("#" + post_id);. Modify the references as appropriate on L11 and L33.
L13: Your code for appending the modal is nice in terms of the builder pattern, but it might be better just as:

var modal = $("

").appendTo("body")

L14: There's no point in declaring the ajaxURL variable. Instead, just go ahead and use { ... url: MyAjax.ajaxurl, ... } on L17,
L20: The jQuery API documentation on .html() notes a specific case in which it's important to use .empty().html(). I don't believe this applies in your case; you don't need the call to .empty() since .html() will effectively empty the container first.
L21: Since jQuery 1.7, .on() is preferred.
L58-59: This part is at best senseless and wrong, and at worst unintuitive and potentially deceptive. By extracting the ID attribute and using it as a selector, you're effectively matching against the ID without the #. This either means that it doesn't do what you think it does, in which case you should use:

jQuery(this).closest("div").foundation("reveal", "close");

or you for some reason have a construct like
 and you really mean to match all span elements instead of #span. In that case, I strongly suggest you restructure your HTML to be more semantically sensible, and to leave a comment explicitly detailing that that's your intention.


Access View from current/corresponding ViewModel

You have multiple options

a. Use an event Aggregator where publish the message from the viewmodel and subscribe from view. see prism documentation for event aggregators:here is sample code

 //view will subscribe from this message
_aggregator.GetEvent<CloseEvent>().Subscribe(CloseAction);

 private void CloseAction(string s) { //do your logic }
 //view model will pubilsh this request
 _aggregator.GetEvent<CloseEvent>().Publish(output);

b. create an interface named as IView and implement it in your view , pass the instance of IView to data context of the view

public partial class Shell : Window ,IView
{
    public Shell()
    {
        InitializeComponent();
        this.DataContext.View = this;
    }

    public void CloseShell()
    {

    }
}

public interface IView
{
    void CloseShell();
}

by using this you have only a reference of interface will be there in viewmodel . but not the whole view itself


How to re register dynamic scripts registered with ClientScriptManager in asp dot net using session was bad idea

Would it not be better to build a generic script to handle all row scripting requirements, and include once per page? You'll end up with a cleaner end script, and your page footprint will be a lot smaller. You'll also benefit from the browser's resource caching.

Using jQuery, you could achieve something like:

$(function() {
    $("tr.needEvent td").live(function() {
        // Event handler code goes here.
    });
});

where tr.needEvent is a class appended to the <tr> used to wrap a row. If you aren't using tables, this could be used the same way with <div> or any other container element. The important thing is, using .live() we can run the code once, and any other elemnets added to the page that match that selector, will be bound to the event handler automatically.

The use of $(function() { is the jQuery equivalent of Sys.Application.add_load(function() {


Rotate image 90 degree clockwise recursively

Nitpicks

using matrix = std::vector<std::vector<T>>;

The standard is to capitalize names of user defined types, so matrix should be Matrix.  I may have misled you in my other review, so I edited it for clarity.

// for debug info
static size_t numTotalSwaps = 0;

While I understand that it can often be helpful to define a global variable to do some quick and dirty debugging, by the time that you are sending code out for code review, this should be gone.  You should be done debugging your code, so you can leave just the actual code.

What I would actually like to see here are the results.  Given a particular input, what is the output?

if (row == image.size())

This can be fragile.

if ( row >= image.size() )

By switching to the inequality, you can avoid a class of bugs where you start incrementing by more than one row at a time but don't update your gate condition.  The check costs the same either way, so you might as well do the more expansive check.

if (row != column && row < column)

This is redundant.  If row < column, then you know that row != column.

if ( row < column )

This is sufficient, as it covers both cases.

    std::reverse(image[row].begin(), image[row].end());
    std::swap(image[row][column], image[column][row]);

I find this harder to follow than just saying

    std::swap(image[row][column], image[image.size() - 1 - column][row]);

I'm not sure which performs better.  It might be worth profiling if that matters to you.

    for (const auto& j : i)
    {
        std::cout << std::setfill(' ') << std::setw(3) << j << ' ';

I don't know what i and j are here.

    for ( const auto& element : row )
    {
        std::cout << std::setfill(' ') << std::setw(3) << element << ' ';

Now I can easily see what I'm printing.  Using i and j didn't tell me what they actually were, but row and element do.

Move Semantics

matrix<T> rotateImage(matrix<T>&& image, size_t row = 0, size_t column = 0)
        return image;
    return rotateImage(std::move(image), row, column);
    for (const auto& i : rotateImage(std::move(image)))

This seems a bad place to use move semantics.  Note that the point of move semantics is to avoid doing a copy when you don't need to do so.  However, here it may create a copy that you don't need.  Note that your algorithm passes an rvalue reference to the function but returns an lvalue.  If each recursive call triggers a full copy on return, your algorithm goes from \$O(n^2)\$ to \$O(n^4)\$.

You might be able to fix this by saying

        return std::move(image);

This will turn the named variable image back into an rvalue reference.

We shouldn't need to pass by value inside the recursive function.  We can work with the actual matrix.  We need to make one copy at most to avoid changing the variable outside the function.

const Matrix<T> & rotateImage(Matrix<T> & image, size_t row = 0, size_t column = 0)
    return rotateImage(image, row, column);

And then insist outside

    Matrix<int> rotatedImage = std::move(image);
    for ( const auto& row : rotateImage(rotatedImage, 0, 0) )

This makes a more regular use of move semantics.  If there is an assignment function that uses move semantics, this will just work.

We also enjoy the speed advantages of working with a reference when dealing with the recursive function.  We don't have to worry if move semantics get used or not, as our function always passes a reference.  We don't force the caller to use std::move, which is more commonly used with an assignment or copy constructor.

At the same time, I added the starting row and column numbers back.  I don't think that the code will work without them.  It looks like they got lost in an edit.

Recursion

The normal advantage of using recursion is that it allows for a more elegant solution.  However, in this case, I don't think that it does.  Your iterative solution traversed the grid smoothly and understandably.  The recursive solution is more complex, as you have to transform the grid into a one dimensional object.

It's also problematic in that the caller has to understand more than it should about what's happening internally.  It has to call std::move and add the initial row and column numbers.  You can sort of fix this by providing two functions.  The first function for use by the caller.  The first function then calls the second function with the right arguments for the recursion.  The second function does the actual work.  Note that it makes sense for the second function to use references.  The first function could pass by value.  Calling with std::move would trigger move semantics on the copy constructor.

The problem with recursion is that it works by making use of the stack.  For each function call, you have to push the current state onto the stack.  However, most of the state doesn't change from call to call, so saving it is redundant.  Further, since this is tail recursion, we're done with the current state by the time that we save it.  A good compiler will optimize this out, but why not go ahead and do it yourself?

Rather than relying on the compiler to fix things, just write the iterative version.  Tail recursion will have a natural transformation into an iterative solution.  In this case, we can do even better.  The recursive solution maps the grid into a vector.  An iterative solution can work with a grid directly.


Filtering data on basis of attribute values

Your code appears to be incomplete but I've provided some ideas below.

Filters Class

I'm looking at your Filters class:

public class Filters
{
    public long Id { get; set; }
    public IEnumerable<string> Value { get; set; }
}

From this, I am assuming that the purpose of this is to hold the Attribute Id (key) and Search Keywords (value). So, I would propose you just use a Dictionary<long, List<string>> -- note that I changed the type of your Search Keywords to a List as I am not seeing any reason within your code example as to why it should/would need to be an IEnumberable type.

That would then change the method:

Method renamed
Parameter updated to use Dictionary instead (per above)

Here is the updated method

public IEnumerable<Product> FilterProductsByAttributeId(
    Dictionary<long, List<string>> filters,
    IEnumerable<Product> products)
{
    // your method contents here
}

Filter Method

I'm not sure why you have a complicated initializer for your tempProducts, but maybe it can be improved to something like this?

public IEnumerable<Product> FilterProductsByAttributeId(Dictionary<long, List<string>> filters, IEnumerable<Product> products)
{
    if (products == null) throw new ArgumentNullException(nameof(products));
    if (filters == null) throw new ArgumentNullException(nameof(filters));

    IEnumerable<Product> result = new List<Product>();
    foreach (var f in filters)
    {
        result = result.Union(products.Where(p => p.ProductAttributes
            .Where(a => a.AttributeId == f.Key && f.Value.Contains(a.Value)).Any()));
    }

    return result;
}

Alternatively you can use the Aggregate extension:

return
    filters
        .Aggregate(
            new List<Product>(),
            (current, next) => current.Union(..)
        );


Two things which are good to know about JAXB:

You can annotate private methods and fields, JAXB can call/modify them. It could help hiding internal data structure from clients.
Marshaller as well as Unmarshaller has event callbacks. They can help handing deprecated or compound fields.

Just two small notes about the code:

I would call the class JaxbConfigurator. Lowercase letters are easier to read. (Effective Java, Second Edition, Item 56: Adhere to generally accepted naming conventions)
It would be worth checking input parameters in the constructor to avoid latter mysterious NullPonterExceptions:

import static com.google.common.base.Preconditions.*;

...

public JaxbConfigurator(final Class<T> toConfigure, final String xmlFilePath) {
    this.clazz = checkNotNull(toConfigure, "toConfigure cannot be null");
    this.filePath = checkNotNull(xmlFilePath, "xmlFilePath cannot be null");
}


How to make this special binary-search algorithm more rusty?

As always, the interface provided by LeetCode is atrocious.  In order to make your code Rusty, I recommend writing your own interface first and then call it within the implementation of LeetCode's interface.  Here's why.
The full interface of the search function, imposed by LeetCode, is
impl Solution {
    pub fn search(nums: Vec<i32>, target: i32) -> i32 {
        // ...
    }
}

Unfortunately, every single part — no exaggeration here — of the interface can be improved.

struct Solution is completely unnecessary in Rust.  It is much more idiomatic to define search as a free function or a trait method.

The name search does not indicate the assumptions on nums clearly.  I prefer something along the lines of rotated_binary_search.

Since the function only reads the contents of nums, there is no need to take ownership of the argument.  Moreover, the function can be made more generic by taking a slice instead of a Vec — see Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?.

The i32s in the types of nums and target aren't unidiomatic per se, but since the same algorithm applies to any type with a total order, a generic type T: Ord is even better.

The return type i32 is problematic for two reasons:

Rust uses usize for indexes, not i32, so returning i32 introduces gratuitous type conversions.

The absence of the target value is signaled by -1, which is error-prone, as the caller may easily forget to check the return value against -1.

Instead, Option<usize> should be used so as to take advantage of the type system.

Here's the improved interface:
pub fn rotated_binary_search<T: Ord>(nums: &[T], target: &T) -> Option<usize> {
    // ...
}

The implementation is of much better quality than the interface.  The last line return -1; can be simplified to -1 (without the semicolon), as the last expression in a function is implicitly the return value.  Then, we can adjust the returns to the new interface — return Some(index) and return None surely read better than -1, right? :)
Now, let's look at the implementation of binary_search (and binary_search_for) in the standard library for inspiration: (ll. 2077–2176, documentation and attributes omitted for brevity)
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
where
    T: Ord,
{
    self.binary_search_by(|p| p.cmp(x))
}

pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
where
    F: FnMut(&'a T) -> Ordering,
{
    let s = self;
    let mut size = s.len();
    if size == 0 {
        return Err(0);
    }
    let mut base = 0usize;
    while size > 1 {
        let half = size / 2;
        let mid = base + half;
        // SAFETY: the call is made safe by the following inconstants:
        // - `mid >= 0`: by definition
        // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...`
        let cmp = f(unsafe { s.get_unchecked(mid) });
        base = if cmp == Greater { base } else { mid };
        size -= half;
    }
    // SAFETY: base is always in [0, size) because base <= mid.
    let cmp = f(unsafe { s.get_unchecked(base) });
    if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
}

The major difference is the use of a (base, size) pair instead of a (low, high) pair, which greatly simplifies the control flow.  You can also use unsafe to eliminate bound checks, but I wouldn't recommend that except when performance is absolutely critical.


Reuse a base class [Activity] handler in all sub classes for background work

You make some assumptions about your window in this line:

mHandler = getWindow().getDecorView().getHandler();

As mentioned by the Activity docs for getWindow()

  Returns
  Window The current window, or null if the activity is not visual

Okay. NullPointerException number 1 waiting to happen. Interestingly #getDecorView() seems to be guaranteed to not return null, which is good. One place less where this can fail.

It is irrelevant whether the returned handler is null or not, because luckily that's what this is about.

Other nitpicks:

Don't use Hungarian notation. mHandler should be just handler. Your IDE is perfectly capable of telling you that handler is a member of type Handler
Failing to reuse an activity handler is not something I'd categorize as Warning.
The comment you place there is partly restating the obvious. Drop the second sentence.


Best approach on handling function that returns either a promise or just synchronous code

You really don't want a function sometimes returning a promise and sometimes returning a value.  That just makes it difficult for the caller.  Instead, if you sometimes have a promise to return, then you should always return a promise.

function isActive(){
  if(condition){
    return API.someFunction().then(function(response){
      return response;
    });
  }
  return Promise.resolve(active);
}

Then, your caller can just know that it always returns a promise and they can code accordingly.  When you have complexity like this, it's better to encapsulate it in the function itself rather than make every single caller deal with it.

So, the caller can then always and consistently just do:

isActive().then(...).catch(...);

Also, if you actually have this in your real code:

   .then(function(response){
      return response;
    });

then, you can remove that entirely and just use this as it generates the exact same result, but is less code:

function isActive(){
  if(condition){
    return API.someFunction();
  }
  return Promise.resolve(active);
}

Both examples return a promise that resolves to response.  One is obviously a lot simpler than the other.


If the algorithm was taken from a book, then chances are it will be as good as it could possibly be.  So as long as you followed it to the letter, there really shouldn't be any issues in your implementation.

There is however one thing I think could be improved upon, the interface to initiate the sort.  When I think of sorting a collection, I'd expect to provide a couple of things, the collection of course and possibly a comparer.  Anything else that requires passing implementation specific values just feels "wrong" to me.  It might be ok if these indices represented the start and stop range of values to sort, but I would still make that as a separate overload.

Your implementation on the other hand requires the collection and indices necessary for the algorithm to work.  This would not be an ideal interface to work with since you have to remember to pass in certain values to perform the sort when instead they could be calculated for me.  I would expose an overload which only accepts the collection to sort which would call the actual implementation with the right arguments.

Also, even though this is the well known quick sort algorithm, I'd still provide better variable names.  Not really a problem here, personal preference.

// this overload is the public interface to do the sort
public static void quickSort(int[] collection)
{
    quickSort(collection, 0, collection.length - 1);
}

// note: method is now private
private static void quickSort(int[] collection, int pivotIndex, int rangeIndex)
{
    // etc...
}


Deleting all the matching items in single linked list

Several issues jump in the eyes:

very complicated logic
very strange "removal" logic: copy value from next node + delete next node
is recommended to use braces even on single statement if-else
messy indentation

This can be done a lot simpler, by using a dummy node:

ListNode dummy = new ListNode();
dummy.next = head;

ListNode runner = dummy;
while (runner.next != null)
{
    if (runner.next.val == val)
    {
        runner.next = runner.next.next;
    }
    else
    {
        runner = runner.next;
    }
}

return dummy.next;


Functional way to have two toggles that turn each other off

The logic itself is simple enough. I see that you are using ECMAScript 6, with it there are some things you could do to simplify the code and make it more robust.
const
You are using let for unscheduledLayerToggles and availableLayerToggles, which is fine, but in the case that you will not be reassigning different values/arrays to those names, you could simply use const instead of let. Note that this will not make the arrays immutable, so you can still manipulate their contents, it only disallows assigning something different to them.
flipToggles function
In the same manner as you can use const to declare function (in the style of var foo = function () { ... }). It helps to make the intentions clear that the function will not change.
Arrow functions
ES6 provides a great way to both shorten/simplify function declarations, as well as isolate their scope better: Arrow Functions.
The syntax is explained well on MDN like I provided. In the case of your flipToggles function, we could write the code this way and eliminate all the unnecessary function() declarations.

const unscheduledLayerToggles = [unscheduledLayerToggle, unscheduledLayerToggleToolbar];
const availableLayerToggles = [availableLayerToggle, availableLayerToggleToolbar];

flipToggles(firstToggles, secondToggles)
flipToggles(secondToggles, firstToggles)

const flipToggles = (firstToggles, secondToggles) => {
  firstToggles.forEach(toggle => {
    on(toggle, "change", () => {
      secondToggles.forEach(element => {
        element.checked = false
      })
    })
  })
}

(mind the indentation, which is a personal preference of mine for 2 spaces indent instead of 4)


xor_break_cookie is almost exactly the same as xor_gen_cookie. I'd change them to be the same function, xor_repeat, with varing input.
Rather than using a[i] ^ b[i % len(...)] for i in range(len(...)), you can use zip, and itertools.cycle.

v ^ r for v, r in zip(value, cycle(repeater))

Rather than using str.encode('abc'), you can use 'abc'.encode(). It also doesn't make sense to use str.encode, it's un-common to see in Python, and provides no benifit here.
Rather than using bytes('abc'.encode()) you can just use 'abc'.encode().
Rather than ''.join(...).encode(), you can use bytes(...).
In decode_base64, if you merge the modifications of missing into one line you get:

missing = 4 - (len(data) % 4) if (len(data) % 4) != 0 else 0

This can be simplified if you use two modulos, rather than an if. \$(4 - i \% 4) \% 4\$.
This however can be further simplified, if you make the left hand side negative, and so you can use \$-i \% 4\$.

And so I'd use:

def decode_base64(data):
    return base64.decodestring(data + b'=' * (-len(data) % 4))

You can ensure that len(substring) > 1, if you start x at y+1.
It doesn't make sense to me to generate values, and also find the max in the same function. Split them apart.
By splitting the generating code, and the max finding code apart, you can use max:

max(_repeated_substring(text), key=lambda t: (len(t), text.count(t)))

Rather than having \$O(n^3)\$ time complexity, you can get a \$O(n^2)\$ time and \$O(n)\$ space complexity solution by using Counter.

In all I'd use something like the following. I also provide the above two ways to find the maximum:

import base64
from itertools import cycle
from collections import Counter

def xor_repeat(value, repeater):
    return bytes(v ^ r for v, r in zip(value, cycle(repeater)))

def decode_base64(data):
    return base64.decodestring(data + b'=' * (-len(data) % 4))

def _repeated_substring(text):
    for i in range(len(text)):
        for j in range(i+1, len(text)):
            yield text[i:j]

def repeated_substring(text):
    return max(_repeated_substring(text), key=lambda t: (len(t), text.count(t)))

def repeated_substring(text):
    vals = Counter(_repeated_substring(text))
    return max(vals.items(), key=lambda i: (len(i[0]), i[1]))[0]

BREAK_JSON = b'{"showpassword":"no","bgcolor":"#ffffff"}'
GEN_JSON = b'{"showpassword":"yes","bgcolor":"#ffffff"}'

if __name__ == '__main__':
    cookie = decode_base64(b'ClVLIh4ASCsCBE8lAxMacFMZV2hdVVotEhhUJQNVAmhSEV4sFxFeaAw')
    password = repeated_substring(xor_repeat(cookie, BREAK_JSON))
    new_cookie = xor_repeat(GEN_JSON, password)
    print(base64.encodestring(new_cookie).rstrip())


Calculating the Nth number in the supertable of two numbers

If I just look at the code, without looking at the algorithm, here's something you could optimize:

String[] input=br.readLine().split(" ");
if(input[0].equals(input[1])){
    System.out.println(Integer.parseInt(input[0])*Integer.parseInt(input[2]));
}else{
    for(int i1=1;i1<Integer.parseInt(input[2]);i1++){
        sort.add(Integer.parseInt(input[0])*i1);
        if(sort.size()==Integer.parseInt(input[2]))
            break;
        sort.add(Integer.parseInt(input[1])*i1);
        if(sort.size()==Integer.parseInt(input[2]))
            break;
    }
    System.out.println(sort.toArray()[Integer.parseInt(input[2])-1]);
}

What's up with all the parseInt? I have a feeling parseInt is very expensive.
So let's do that only once.

No matter what you do, you always need input[2] and input[0].
You only need input[1] once you reach the for loop, so I've moved the declaration near the for loop.

String[] input=br.readLine().split(" ");
int input0 = Integer.parseInt(input[0]);
int input2 = Integer.parseInt(input[2]);
if(input[0].equals(input[1])){
    System.out.println(input0*input2);
}else{
    int input1 = Integer.parseInt(input[1]);
    for(int i1=1;i1<input2;i1++){
        sort.add(input0*i1);
        if(sort.size()==input2)
            break;
        sort.add(input1*i1);
        if(sort.size()==input2)
            break;
    }
    System.out.println(sort.toArray()[input2-1]);
}

There's probably a greater optimization to be made on a algorithmic level, but this at least fixes one issue.


Does this code actually give a valid representation of how quick a system is?

No, your benchmark is completely bogus. Let's look at the main loop:

while millis() - start < 1000:
    x = 4+5
    #counting up
    count = count + 1

The addition 4+5 can be constant-folded when the code is compiled. If you are lucky, the assignment remains although a constant assignment might be lifted out of the loop.

But aren't we then still benchmarking the counter increment? Likely, no. The function call millis() in the loop condition is probably at least an order of magnitude more expensive. So essentially, you're benchmarking how fast you can check whether you're done with benchmarking.

The next problem is which time you are measuring. You are currently measuring the elapsed wall clock time (sometimes: “real” time), i.e. the time that you observed passing. However, this is not the same as the time your loop spent executing, because the operating system is free to interrupt execution to schedule other processes in between. The correct time to measure is the “user” time to see how much your program itself worked, and the “system” time to see how much the OS kernel worked on your program's behalf via system calls. The used CPU time is the sum of user and system time. This paragraph uses Unix terminology, but the problem is the same on Windows.

All of this is complicated, so don't do it yourself. Python has a timeit module where you can measure how long a function took to execute a specific number of times. The number of iterations per second is then the inverse of the time spent executing. To prevent the overhead of the function call from affecting the result, the timed function should include a loop itself, e.g. with a million iterations. To execute the body of the loop 10M times, you would then time the function ten times etc.

Edit: code example

Assuming Python 3.3 or later, we can use the time.process_time function which measures the used CPU time of our process.

import time
import timeit

n = 10000000 # 10M
timings = timeit.repeat(
    setup='x, y = 4, 5',
    stmt='z = x + y',
    timer=time.process_time,  # comment this line for pre-3.3 pythons
    number=n
)
best_time = max(timings)
repetitions_per_second = n/best_time
print("repetitions per second: %.2E" % repetitions_per_second)

Unfortunately I can't test it right now because I don't have Python 3.3 or later installed. So we might have to use a timer that uses wallclock time instead – this isn't so catastrophic because repeat will take three measurements, and we'll use the best. This does not eliminate the effect of scheduling, but it does minimize it.

Example ballpark results:

           3.2     2.7
Machine 1  <= 6E6  = 1E7
Machine 2  <= 2E7  > 2E7

So with a back of the envelope-calculation, we can say that machine 2 is roughly 2–3 times as fast as machine 1. This is consistent with their specs (desktop vs. low-end server).


better way of such parsing is not to reinvent the wheel and use existing ruby functionality

require "cgi"
post = CGI.parse "a=b&c=d"
# => {"a"=>["b"], "c"=>["d"]}

hash values are arrays here, but it makes sense, as you can have several vars in your query string with the same name

for the second part of your question (accessing the keys as symbols) you can use .with_indifferent_access method provided by ActiveSupport (it is already loaded if you use rails)

post.with_indifferent_access[:a]
# => ["b"]


create a lookup of all tracked trains for each wagon

That's pretty much what the ToLookup() method is for. You just need a bit more LINQ  to get a collection of (train, wagon) pairs, so that ToLookup() can work:

var wagonTrains =
    (from train in trains
     from wagon in train.WagonsInTrain
     select new { train, wagon })
        .ToLookup(x => x.wagon, x => x.train);


TextField Validation for Teleport Feature in Game

Table organization

this.menuTable.setPosition(this.stageWidth/10, this.stageHeight/8);
this.menuTable.setWidth((float)(this.stageWidth * 0.8));
this.menuTable.setHeight((float)(this.stageHeight * 0.6));

I have mentioned before that I do not like this. This is not the "correct" way to setup a table on your screen. When you solve this issue, you will no longer need to pass around stageWidth and stageHeight.

Guess what the magic number is today?

this.menuTable.add("Latitude 0 - 50");
this.menuTable.add("Longitude 0 - 50");

Extract 50 to a static final int constant and use string concatenation to set the string:

this.menuTable.add("Latitude 0 - " + MAX);

processTextField

The first thing that comes to my mind is: If a user enters invalid input, should they then really be teleported?

If I enter the coordinate -42, 1not2a3number4, I would expect an error message, not being teleported to (0, 0). Also remember that users will not be able to see System.out.println output.

That being said, I'd also make some other changes:

Use int instead of Integer for position variable
Instead of if (position < 0) do position = Math.max(0, position);
Instead of if (position >= MAX) do position = Math.min(MAX, position);

The both Math.max and Math.min uses can be put together into:

position = Math.min(MAX, Math.max(0, position));

However, there is a LibGDX method in MathUtils that already does this:

position = MathUtils.clamp(position, 0, MAX);


Calculate EMI based on principal, rate, duration (month or years)

In the comments to your other questions some things were mentioned that are also applicable to this question as well, like:

Try to follow PEP 8 style guide.
Single letter names should be avoided.
Avoid useless comments, make your code self explanatory.
Check for invalid input, raise exceptions.

Now, you have some magic numbers like 12, 100 and 4. Give them names. Make them constants. Don't leave them like that.

Some prints don't make a lot of sense, like printing type of R or printing if duration is in years or in months. That looks more like information for debugging. I suggest you to take a look at logging module and give it a try. But for such a small program it is probably an overkill.

This n = d[0:(len(d)-1)] is repeated twice in your code and it can be taken out of that if-elif statement. Moreover it can be simplified as n = d[:-1].

Instead of writing

EMI = x*(P*r*(1+r)**m)//((1+r)**m - 1)
return EMI

you can write just

return x*(P*r*(1+r)**m)//((1+r)**m - 1)

Finally, wrap your print EMI_calculator(10000,12,'Q','3Y') like this:

if __name__ == '__main__':
    print EMI_calculator(10000, 12, 'Q', '3Y')

You can read about it here.


You can minimize you code taking out the filtering out side of loop.
Avoid catching exception inside a loop if it needed ,(it seems like it cannot be avoided here)
No need to invoke datarow extension method to get value , you can get it directly.
Naming of variable is really bad.

This is first round of re factoring.

public static T[] MapObjects<T>(DataTable dataTable, Func<PropertyInfo, bool>
 propRestriction) where T : new()
{
var mappedObjectProperties = typeof(T).GetProperties()
                                       .Where(elem => !propRestriction(elem)).ToList();
var mappedObjectCollection = new List<T>();
foreach (var dataRow in dataTable.AsEnumerable())
{
    var mappedObject = new T();
    foreach (var mappedObjectProperty in mappedObjectProperties)
    {
        if (dataTable.Columns.Contains(mappedObjectProperty.Name))
        {
            var value = dataRow[mappedObjectProperty.Name];
            mappedObjectProperty.SetValue(mappedObject, value, null);
        }
        else
        {
            log.Debug("Nothing to set for property: {0}", prop.Name);
        }
    }
    mappedObjectCollection.Add(mappedObject);
  }
  return mappedObjectCollection.ToArray();
}


Yeah, you can simplify your code. To have a single method for both of them, you would need to specify whether the check was negated and what action to perform (that could be done using a delegate).

To simplify it even more, use a loop over the three boxes (possibly using a Dictionary to connect each box to the date part).

Also, when working with DateTime.Now, you should make sure to access that property only once, then use its value. If you don't, you could get inconsistent results if the time changes while your method is executing.

private void AddValues()
{
    ProcessValues(true, (items, value) => items.Add(value));
}

private void RemoveValues()
{
    ProcessValues(false, (items, value) => items.Remove(value));
}

private void ProcessValues(
    bool negateContains, Action<ListBox.ObjectCollection, int> successAction)
{
    var now = DateTime.Now;

    var pairs = new Dictionary<ListBox, int>
    {
        { box_Hour, now.Hour },
        { box_Minute, now.Minute },
        { box_Second, now.Second }
    };

    foreach (var pair in pairs)
    {
        bool condition = pair.Key.Items.Contains(pair.Value);

        if (negateContains)
            condition = !condition;

        if (condition)
            successAction(pair.Key.Items, pair.Value);
    }
}

This makes your code less repetitive, but also more complicated. It's up to you to decide if that's worth it.


Method to replace all spaces in a String with '%20'

It's important to pay attention to every bit of detail in the problem description:

  Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)

As you're implementing this in Java, your method should receive a char[] instead of a String. And if I interpret correctly, the "true" length is the length without the padding, and is an additional parameter, giving the signature:

void replaceSpaces(char[] input, int trueLength) { ... }

With this established, the implementation can be simplified:

No need for getTrueLength: it's a given
No need for calculating the final size, it's given by input.length

As @rolfl pointed out, the size of input is not 100% clear. The description only states that it has sufficient space. So indeed, we may need to calculate the final size.

The printing is unnecessary and should be removed, as it breaks the single responsibility of the method

Another improvement in the implementation is that you don't need to count the spaces. You can walk backward, tracking two positions in parallel:

The last position to write to (starts at input.length - 1)
The last position in the text (starts at trueLength - 1)

Walk backward as long as the text position is smaller than the end position. If you see a space, overwrite the the values at the position with %20. Otherwise simply copy the input.

void replaceSpaces(char[] input, int trueLength) {
    //int end = input.length - 1;
    int end = trueLength + (countSpaces(input, trueLength) * 2) - 1;
    for (int textEnd = trueLength - 1; textEnd < end; textEnd--) {
        if (input[textEnd] == ' ') {
            input[end--] = '0';
            input[end--] = '2';
            input[end--] = '%';
        } else {
            input[end--] = input[textEnd];
        }
    }
}


Use a comma-separated field in another SQL query

It's a very weird database schema in the first place.

There should be never a thing like comma-separated values in one cell. Learn the database normalization and then create a link table wghich can be used to get all your records in a single query with JOIN.

There should be never a thing like multiple tables of the same structure. there should be only one table with a field to distinguish the kind of domain.


SkipLast of an IEnumerable - Linq Extension

There are 2 cases for which both your and VisualMelon's implementation can be improved:

If count is less than or equal to 0, then you can return source directly. This speeds up iteration by removing an unnecessary intermediate step. For this to work, the yielding part of the method has to be moved into another method, but that's easy with local functions.
If source is ICollection<T> collection, then you can return source.Take(collection.Count - count), which is faster and uses less memory because it doesn't need to buffer anything. The higher count is, the more of a difference this makes.

The first of these is probably not a very useful edge-case, so it might not be worth the extra code, but I would definitely include the second optimization.


This is a Monoid instance I wrote for a Tree data type. Is this the most terse way to express mappend?

You can remove mappend Empty Empty = Empty because that case will be caught by mappend Empty t = t.

instance (Monoid a) => Monoid (Tree a) where
    mempty = Empty
    mappend Empty t = t
    mappend t Empty = t
    mappend (Node val ta tb) (Node val' ta' tb') = (Node (mappend val val') (mappend ta ta') (mappend tb tb'))


Calculate distance between points and price per area in Pandas

The problem you are having is most likely due to your code being O(n²) on the size of your dataframe. (It's possible you have a small df and a really bad implementation of geo_dist, but I'll ignore that.)

Let's strip out most of your code:

for index, row in df.iterrows():
    df['distances'] = df.apply(lambda x: geo_dist(point, [x['latitude'], x['longitude']]).km, axis = 1)

These lines can be rewritten:

for index, row in df.iterrows():
    for i, r2 in df.iterrows():
        p2 = (r2['latitude'], r2['longitude'])
        df.distances[i] = geo_dist(point, *p2).km

The same is true for the filtering of distances < radius/1000: you are looping over all n rows, and then for each row you are looping over all n rows again. This is n * n operations, or O(n²).

There is no simple way to fix this. If you insist on computing the distances from each point to its surrounding points, you will have to structure your code this way. However, there are some alternatives:

You could use a kd-tree or a space partitioning hash of your own design to access your points. This would make pandas secondary in your access, requiring you to write more python code yourself.
You could take advantage of some other heuristic to determine proximity, and use this to filter your data before running your n² algorithm on it: note that 3² + 3² = 18, while (3 + 3)² = 36. Breaking your data down into smaller units can have a substantial impact on your performance. For example: in the United States, zip codes within a given state all start with a few identical 2 digit prefixes. You might build a dictionary of "adjoining" states, by hand, and then pre-filter your locations using a zip-code prefix, such that you only consider other points that have the same 2-digit prefixes, or the 2-digit prefixes of an adjacent state. If your locations were US cities, this would let you eliminate more than 90% of your data before you start your n² algorithm.
There are surely some other approaches, which will tend to vary based on your application. Perhaps if you mention what problem you are trying to solve, someone will have a suggestion.


In general your code looks good, here are a few smaller remarks.

Method name:

Capitalize the name of your method and make it more meaningful. Use CountAlphaNumeric or something similar.

Comments in code:

You can omit the comments in your code. It speaks for itself what the code is doing, certainly because you use clear names for your variables.

IsNumeric() - Char.IsDigit():

In the .NET framework, there's the Char.IsDigit method, use this one instead:

If Char.IsDigit(c) = True Then numericCount += 1

MsgBox() - MessageBox.Show():

Although MsgBox is valid, it also comes from the VB era. In the .NET framework there's the MessageBox.Show method, use that one instead:

MessageBox.Show("Number of alphabets : " & alphaCount)

String.Format():

To insert variables in a string, use the String.Format instead of just concatenating the values:

Dim result As String = String.Format("Number of alphabets : {0}", alphaCount)

"Expression = True":

You can leave out the = True part in your if conditions, since the methods return a boolean value.

This is what the code now looks like:

Public Sub CountAlphaNumeric(ByVal input As String)

    Dim alphaCount As Integer = 0
    Dim numericCount As Integer = 0

    For Each c As Char In input
        If Char.IsDigit(c) Then numericCount += 1
        If Char.IsLetter(c) Then alphaCount += 1
    Next

    MessageBox.Show(String.Format("Number of alphabets : {0}", alphaCount))
    MessageBox.Show(String.Format("Number of numerics : {0}", numericCount)

End Sub

Using LinQ:

Although not always the best option, you can achieve the same result using LinQ, using the Enumerable.Count method:

Dim alphaCount = input.Count(Function(c) Char.IsLetter(c))
Dim numericCount = input.Count(Function(c) Char.IsDigit(c))

Here's the complete code using LinQ:

Public Sub CountAlphaNumericUsingLinQ(ByVal input As String)

    Dim alphaCount = input.Count(Function(c) Char.IsLetter(c))
    Dim numericCount = input.Count(Function(c) Char.IsDigit(c))

    MessageBox.Show(String.Format("Number of alphabets : {0}", alphaCount))
    MessageBox.Show(String.Format("Number of numerics : {0}", numericCount))

End Sub


Script to create symlinks for dotfiles in a Git repository

I noticed that some of your questions have similar aspects, so I clustered them to provide a single answer:

"How is my general bash programming style?"
"How can I reduce the number of duplicates?"
"How could I outsource this echoing to the outside of the function?"

Shell script is ugly compared to other scripting languages, so we need to make an extra effort to keep it readable.

So here are some suggestions to improve the readability of your script:

Check your script with ShellCheck for insights on best practices and idioms.
Extract those file checks to functions with meaningful names, so that the reader won't need to remember (or lookup) what each flag means:

if [[ -e "$symlink_loc" ]]; then
    if [[ -L "$symlink_loc" ]]; then

could become:

if file_exists "$symlink_loc"; then
    if is_symlink "$symlink_loc"; then

Hide low level details that are polluting the custom_link function:

custom_link() {
    # 1. checking if original file is valid
        # 1.1 if not valid, print error message and return 1

    # 2. handling existing file where symlink should be placed
        # 2.1 if is already existing symlink
            # 2.1.1 if symlink already points to file, print success and return 0
            # 2.1.2 otherwise, ask user if symlink should be replaced
                # 2.1.2.1 if yes, replace it

        # 2.2 if is a regular file
            # 2.2.1 prompt user to delete, move or keep file
                # 2.2.1.1 if delete, delete file and place symlink
                # 2.2.1.2 if move, create dir $HOME/.other, move file there and place symlink
                # 2.2.1.3 if keep, print "keeping the file"

    # 3. creating symlink
        # 3.1 extract dirname of symlink
        # 3.2 try to create extracted dir
            # 3.2.1 if fails, print error and return 1
        # 3.3 create symlink, print success and return 0
}

It should be easy for the reader of custom_link to understand what is going on, on a high level:

custom_link() {
    file_loc="$1"
    symlink_loc="$2"

    if ! file_exists "$file_loc"
    then
        return invalid_file_error "$file_loc" "$symlink_loc"
    fi

    if file_exists "$symlink_loc"
    then
        return handle_existing_file "$file_loc" "$symlink_loc"
    fi

    create_new_symlink "$file_loc" "$symlink_loc"
}

And then you can hide lower level details of each step on their own dedicated functions. (You can apply this recursively, until the functions are very small and obvious)
Here are some examples:

file_exists() { test -e "$1"; }

invalid_file_error() {
    file_loc="$1"
    symlink_loc="$2"

    echo "${RED}WARNING${RESET}: Failed to link $symlink_loc to $file_loc"
    echo "         $file_loc does not exist"
    return 1
}

handle_existing_file() {
    file_loc="$1"
    symlink_loc="$2"

    if is_symlink "$symlink_loc"
    then
        return handle_existing_symlink "$file_loc" "$symlink_loc"
    else
        return handle_existing_regular_file "$file_loc" "$symlink_loc"
    fi
}

"Any important idioms I missed?"
"How could I implement more successful return values?"

The convention is to return 0 for success and anything else for errors.

So you got it right when you are returning 0 (symlink already there pointing to expected file) and 1 (file doesn't exist).

But when you prompt the user on which actions should be taken, you are successfully executing what was requested, but returning a 2.

If you think from the user's perspective, the exit code should be 0, since the script did exactly what the user wanted.

"Did I miss any important cases?"

The user can choose to move a file to $HOME/.other, but what should happen if there is already a file there (on $HOME/.other) with the same name, maybe from a previous run?


It looks like your logic is fine, but I don't find it very readable. I guess it would be fine if you could clearly explain your logic in a tech interview, but here's how I'd write it just to be more clear.

Use a for loop (that's what they're for!), modify the digits array in place unless they specify you shouldn't, and you can return as soon as you don't have anything left to carry.

var plusOne = function(digits){
    let carry=1;

    for(let i=digits.length-1; i>=0; i--){
        let digitSum = carry + digits[i];
        if(digitSum >= 10){
            digits[i] = digitSum%10;
        }
        else{
            digits[i] = digitSum;
            return digits;
        }
    }

    if(carry == 1){
        digits.unshift(1);
    }
    return digits;
}


Making the code portable again
You did a fine job cleaning up last code's bugs. My answer will be fairly short this time.

How can I avoid having to read from /dev/tty? I know that the device
file is available on practically all Unixes, but it won't work on
Windows.

Well, I have some good news and some bad news.
Bad News
The bad news is that I'm pretty sure the only way you aren't going to get that bug where you substitute the file for STDIN is if you continue reading from /dev/tty. After all, you can't possibly read from STDIN because that's where the file is.

You can stop now. As a quick and smart fix, you can drop support for reading from STDIN (I mean, who would use a pager to read something they are typing into STDIN?). Or, if you want you can read on for the good news.

Good News
There's a solution that allows you to keep on reading from /dev/tty and that is to use the amazing Windows API. Luckily, you can do that in C because Windows provides a header file windows.h that gives you full access to the Windows API in your C/C++ code.
Now, you may think to just include the windows.h file in your code and use whatever the API has to read the keyboard. Well, you can't quite do that because if you try compiling that on *nix, you'll get an error saying that the windows.h could not be found.
An easy fix is to use the pre-processor:
#include <stdio.h>
#include <stdlib.h>

#ifdef _WIN32
#include <windows.h>
#endif

This will make sure to only include the windows.h file if the operating system is a Windows one.
Then, in the section where you would normally open and read from the /dev/tty file, you would encase that in:
#ifdef linux
...
#endif

and the Windows code in the respective pre-processor statements.
As for what actually goes inside the Windows code sections, I am unsure. Through some quick searching, I came across ReadConsole in the API index. However, I have not tested it out. If that does not work, feel free to explore the API for other possibilities.


Verifying if a car is a sports car based on speed and horse power

_maxSpeed and _horsePower should be private.

You have (confusingly named) setter methods for public variables, but no getters.  That makes for an odd interface.

In C# you by convention use properties for getters and setters.  So instead of

public int _maxSpeed = 0;
public int _horsepower = 0;
public void maxSpeed(int newmaxSpeed)
{
    _maxSpeed = newmaxSpeed;
}
public void horsepower(int newhorsepower)
{
    _horsepower = newhorsepower;
}

You have

public int MaxSpeed { get; set; }
public int HorsePower { get; set; }

Since these values are unlikely to change, you could make the type immutable:

class Car
{
    public readonly int MaxSpeed;
    public readonly int HorsePower;

    public Car( int maxSpeed, int horsePower )
    {
        MaxSpeed = maxSpeed;
        HorsePower = horsePower;
    }
}

Instead of checking a boolean expression and then returning a literal true or false, just return the expression instead.  Booleans are a type just like any other.  Also, you don't need the comparison to true or false for the same reason.

if( someCondition == true )
    return true;
else
    return false;

You have

if( someCondition )
    return true;
else
    return false;

or better yet

return someCondition;

So

return _maxSpeed >= _MinimumRequiredSpeed &&
       _horsepower >= _MinimumRequiredHorsepower;

Whenever you take user input you need to check it.  Your program will crash if the user enters something that is not a number.  You can check this by using TryParse instead of Parse.

int horsePower;
do
{
    string input = Console.ReadLine();
}
while( !int.TryParse( input, out horsePower ) );

Other than that it is fine, keep at it ;)


Why do you need the 3 times? Is there a restriction, that the first number may not be 0?

If there  is no 0-restriction, you may generate a number between 0 and 999999.
To get the leading 0 I use the strftime-pattern %06i (6 digit with leading zeros).

  p "QQ%06i%s" % [ Random.rand(999999), ("A".."D").to_a.sample ]

For the letter, you may generate a random number from 65..68 and take the character for the selected ASCII-value (code example is ruby 1.9. Maybe you need a little variation with Ruby 1.8):

  p "QQ%06i%s" % [ Random.rand(999999), (65 + rand(4)).chr ]


I am prejudiced against variables named data.

You need to escape literal ", \, and \n characters in quoted strings.  It's good form to do tabs too.

Using a dispatch table for types (instead of if/else) makes it easy to handle all the types.

Instead of passing tab up and down the call stack, wrap the calls in a function that indents a block of text.  Nested traverse will be nested in indent too and get indented the right number of times.

Instead of checking whether you're at the end of a delimited list (to decide whether to add a delimiter), use arr.join(delimiter). It puts delimiters on inner boundaries only.

Array(n).fill(' ').join(''); is the same as ' '.repeat(n).

It would be nice to omit the quotes on property names that don't need them.  Doing this perfectly happens to be really laborious—the regex is 11 kilobytes long!!  It's manageable if we limit the exceptions to 7-bit ASCII, which is probably a good idea anyway.

function prettyPrint(obj) {
    const stringify = {
        "undefined": x => "undefined",
        "boolean":   x => x.toString(),
        "number":    x => x,
        "string":    x => enquote(x),
        "object":    x => traverse(x),
        "function":  x => x.toString(),
        "symbol":    x => x.toString()
    },
    indent = s => s.replace(/^/mg, "  "),
    keywords = `do if in for let new try var case else enum eval null this true
            void with await break catch class const false super throw while
            yield delete export import public return static switch typeof
            default extends finally package private continue debugger
            function arguments interface protected implements instanceof`
       .split(/\s+/)
       .reduce( (all, kw) => (all[kw]=true) && all, {} ),
    keyify = s => ( !(s in keywords) && /^[$A-Z_a-z][$\w]*$/.test(s) ? s : enquote(s) ) + ": ",
    enquote = s => s.replace(/([\\"])/g, '\\$1').replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/^|$/g,'"'),
    traverse = obj =>  [
           `{`,
            indent( Object.keys(obj)
                    .map( k => indent( keyify(k) + stringify[ typeof obj[k] ](obj[k]) ) )
                    .join(",\n")
                    ),
            `}`
        ]
        .filter( s => /\S/.test(s) )
        .join("\n")
        .replace(/^{\s*\}$/,"{}");
    return traverse(obj);
}

console.log(prettyPrint(
    {
        "name":"Jon",
        "facts":{
            "car":"Ford",
            "address":{
               "city":"New York"
            },
            "watch":"Casio",
            "other": {
                "true":false,
                blargh:undefined,
                "111number":1e5,
                method:function(x){x++}
            }
        }
    }
));


I spotted the following problems:

Exception handling When you catch an exception, you just print its stack trace but then keep going as if nothing happened, forcing another exception a few lines down the code. You should change this
Byte conversion: Your getSalt method converts the byte array holding the salt into a string, the other 2 methods try to convert that string back into a byte array. Firstly, I think that you are doing that conversion wrong. But event if that was not the case, you should not do that. A byte array should be kept as a byte array. Unneccesary conversion can always cause errors. If you absolutely need a string, use Base64 encoding.
You should not simply use SHA256(Salt | password). Use HMAC-SHA256 instead.
Actually, SHA-256 or HMAC-SHA256 are not good functions to hash a password. You should use a dedicated password hashing KDF, which are much better at resisting brute force attacks. Good examples are scrypt, bcrypt, PKBKDF2, Argon2.
I still don't get the strange way you are converting your password hash into a string at the end. Use Base64 instead.
Your essential code (the password hashing) is duplicated in two methods. Don't do that.


I have some suggestion for you.

1) The naming convention of the variables HOUR_IN_SECONDS, DAY_IN_SECONDS and YEAR_IN_SECONDS is not correct, since they are not constant; missing the static keyword. I suggest that you extract them in the class level.

public static final int HOUR_IN_SECONDS = 60 * 60;
public static final int DAY_IN_SECONDS = HOUR_IN_SECONDS * 24;
public static final int YEAR_IN_SECONDS = DAY_IN_SECONDS * 365;

public static void main(String[] args) {
   //[...]
}

2) I suggest that you create a method that take the number of seconds and print the result.

public static void main(String[] args) {
  int seconds = 1000000000;
  printFromSeconds(seconds);
}

private static void printFromSeconds(int seconds) {
    //[...]
}

For the rest, I think it's ok since the variable seconds is closely linked with the other components.


Game of Life in Scala with a sparse representation

You have an interesting implementation. I like your approach into making it "boundless" (that it could expand as-needed). I also like how you use "streams" to compute the values lazily. And some other minor gems.

There are of course some things that you could consider in order to make the design better.

1. Separation of Concerns

The most important thing I would do is to keep the parsing and the formatting separate from the "game". For me, these two concerns should be external to both your internal representation (a set of tuples) and logic.

For example I would have an object (or a class) GameParser and GameFormatter, each with one method to respectively parse and produce a "formatted" string-representation of your GameOfLife object.

(Why not just leave the formatting to toString? In my opinion toString is not there to produce complex formatting, much less "parametrised" formatting (as the "living" and "dead" chars are carried around only for this purpose) but to have an useful, but minimal, string-representation of one object instance. The way I see it, toString is for the developer, not the end-user. Note that for this reason toString implementations often "cut" or "summarize" the contents of the object. It gives you an idea of what the object is about).

You could, then have the same symmetry we see in JSON serializers. There we find readers and writers. You could have something like:

object GameFormatter {

  def formatAsGrid(game: GameOfLife, living: Char, dead: Char): String = {
    // ...
  }

}

object GameParser {

  def parseGrid(board: String, living: Char, dead: Char): GameOfLife = {
    // ...
  }

}

And your main class would become simpler:

case class GameOfLife(liveCells: Set[(Int, Int)] = Set(), width: Int = 0, height: Int = 0) { /* ... */ }

Once you extracted the parsing and formatting to external functions, you could further simplify their parameters. I introduced this case class:

case class GridChars(living: Char, dead: Char)

Which now only the parser and formatter need to be concerned about. We could then change the function signatures to:

def parseGrid(board: String, gridChars: GridChars)
def formatAsGrid(game: GameOfLife, gridChars: GridChars): String

Which would only need to be defined once in your main method, and passed as parameter to both parser and formatter (if so inclined, you could go one step further and dictate this to be an implicit parameter).

I think just these changes so far would make your design simpler, separate concerns better and let your main class have less parameters.

2. The parsing

But you also mention that you are not happy with the implementation of your parser. What do you think of this?

def parseGrid(board: String, gridChars: GridChars): GameOfLife = {
  var maxHeight = 0
  var maxWidth = 0
  val cells = mutable.Set[(Int,Int)]()
  for ((line, rowNr) <- board.lines.zipWithIndex) {
    maxHeight = maxHeight max (rowNr + 1)
    for ((cellChar, colNr) <- line.view.zipWithIndex) {
      maxWidth = maxWidth max line.length
      if (cellChar == gridChars.living)
        cells.add((rowNr, colNr))
    }
  }
  GameOfLife(cells.toSet, maxWidth, maxHeight)
}

I simplified things a little bit:

instead of flatMapping, I am using double-for-loops
I am indulging in "local-scope" mutability: still using the vars you introduced, and also using a mutable set, which poses to the outside world as "immutable".

3. Formatting

It would seem that my code is less functional, less Scala-idiomatic, less fancy, more boring and more Java-esque. And, you would be right! It is a matter of personal preference. My top priority when I write code is for it to be as readable as possible. For me, code which is obvious to the point of being boring is something positive. But that's just me.

For example, and in case it serves any purpose, here is my refactored version of your toString:

def formatAsGrid(game: GameOfLife, gridChars: GridChars): String = {
  import game.{height, isLive, width}
  (for (rowNr <- 0 to height) yield {
    (for (colNr <- 0 to width) yield {
      if (isLive((rowNr, colNr)))
        gridChars.living
      else
        gridChars.dead
    }).mkString // join chars into line
  }).mkString("\n") // join lines
}

It is longer and more verbose. Yet it does the same. I tend to favour longer, more verbose code, but not to the point where meaning is lost.

4. Other Points

There are some other improvements that I want to mention, which could also be considered:

Naming: favouring longer, meaningful names instead of one-letter-variables. For example "colNr" / "rowNr" instead or "r" or "c".
Favouring case-classes over tuples (e.g. Cell, Dimension, etc.)
This is subjective, but I include it here nonetheless: consider using for loops as much as possible (for readability)
Allow yourself to use scoped-mutability if it improves readability
(as a bonus: it might improve performance and produce less garbage)
Favour direct-talking (law of Demeter): ask GameOfLife itself if it's empty, not the cells. Provide a method hasLiveCells.
Scala-style: don't specify an empty parameter list () if your function is pure (has no side-effects)
Name the "main" object (where the main-method is) other than your game-logic-class, since they are not related (the reader could mistaken the object as the companion object of the case-class). Suggestion: GameOfLifeMain.
Something minor: it does not seem right to me that width and height come from "outside". Although less performant I think this could be computed by GameOfLife itself, internally, as soon as it's instantiated.

5. Case-class or not?

To close I want to address another question you had, which I will paraphrase as this:

  Does it have to be a case-class?

The decision is subtle, probably personal, and we enter in philosophical arena. There is of course nothing wrong for this to be a case-class. But personally, in this case, I would not make it so. This is the criteria I use to decide if to make it a case class or not:

Case class if:

It has little to no logic
I expect to do pattern matching on it
I expect for it to be put into collections

Not case class if:

It does contain "business" logic
It does not make sense to put it into a collection
I don't expect to do pattern matching on it

Whether the class is immutable, or I need a "quick" way to instantiate it and have getters (additional features of a case class) is irrelevant to me.

So, I hope this has helped and gave you some insights.


You're a Python native, aren't you? I can tell from the """ multiline strings and the four-space indents and really unidiomatic whitespacing and if/then/else/end instead of ternary and if not instead of unless and use of blocks instead of statements and wow this is really unidiomatic ;-;

Each tip assumes that you've already applied the last.

Also, I'm writing this review from the perspective of Ruby 2.2.2 -- some methods that existed when you wrote this don't exist any more, and some methods that do what you want better have been created. I suggest looking through the Ruby docs for the updated methods, since there's no way I caught everything.

Ruby indents are two spaces, not four.
You may have noticed a bug -- even though you seem to be specifying a single multiline string, it's printing out a bunch of newlines between the beginning and the end. That's because """ [stuff] """ is interpreted not as a single string but as three: "", " [stuff] ", and "". Then, it outputs each of those on a new line, which results in a bunch of extra spacing. It also doesn't eliminate the indentation, so it ends up being moved really far to the right, too.

To fix both issues, you can use a heredoc:

else
  self.tap {|x| puts <<-END.gsub(/^\s*\||#@.*$/, '')
                  |
                  |    |
                  |    |    #{previous_method}
                  |    |
                  |    V
                  |
                  | #{repr}
                END}
end

In multiline blocks, use do/end instead of {/}:

else
  self.tap do |x|
    puts <<-END.gsub(/^\s*\||#@.*$/, '')
      |
      |    |
      |    |    #{previous_method}
      |    |
      |    V
      |
      | #{repr}
    END
  end
end

Actually, why are you using self.tap at all? Just do the puts, then return self after:

else
  puts <<-END.gsub(/^\s*\||#@.*$/, '')
    |
    |    |
    |    |    #{previous_method}
    |    |
    |    V
    |
    | #{repr}
  END
end
self

In Ruby, we have the ternary operator (condition ? a : b). Use it instead of the one-line if/then/else/end construction:

repr = (self.class == Enumerator) ? self.to_a : self

But even that's unnecessary -- firstly, to_a returns an Array, not an Enumerable. Secondly, calling to_a on an Array will return the unmodified array, so you can just write:

repr = self.to_a

Of course, this is a bad idea. What happens when someone tries to use your .log with an IO? Should the entire contents of the IO be put into an array? That seems really stupid to me. Personally, I would instead have

repr = self.to_s

Since, after all, you'll be printing it, and it's far better to let the designers of an object decide how it ought to be printed, rather than trying to wrest control from the developer using the library.
You know, repr is really a crappy name. What does it mean? You can feel free to have long variable names in Ruby; just make sure they're in snake_case.
What is this?

if [Array, String].include?(repr.class) and repr.length > 100
  repr = repr.first(20) + [". . ."] + repr.last(20)
end

You already forced repr to be a String (and in your code, it was already an Array). Why are you checking that again? Plus, if it's a String, then it'll fail when you try to call the nonexistent first on it! Besides, Array and String aren't the only classes with a .length method. This is how I'd do it (keeping in mind that in #6 I converted it to a String):

repr = repr.length > 100 ? "#{repr[0..20]}. . .#{repr[-20..-1]}" : repr

For more information about String#[], see the docs. I'd also recommend pulling this out into a method -- the method name is up to you, but I'd personally call it shorten or trim_extra_chars or something like that.
previous_method really isn't a very good name. It's not necessarily method that came before, after all -- it's an operation that led to the current state. It could well have been something that isn't a method! I'd call it previous_operation.
What happens when someone wants to log a method called start? For example, say they have an object representing a task that's built over several chained method calls, then started with start, which returns the result of the task. They'll try to .log('start'), but it'll instead give them this weird thing that they didn't expect! I'd recommend splitting it into two methods -- then, instead of an if/else and a default value, you can have:

def log_start
    #etc.
end

and

def log(previous_operation)
    #etc.
end

One bonus of this (combined with #8) is that you can totally get rid of repr.
Now, there are a couple of other things: Very rarely do people want to log stuff to the console (i.e. where puts goes). I'd recommend adding support for outputting to other streams, though there are a couple of ways to do it. One of them, my personal favorite, involves a lot of metaprogramming and probably isn't worth it. Another is just to add a parameter output=$stdin and replace all calls to puts with output.puts to log_start and log.
Lastly, I did some changes in the actual output, just because it looks nicer IMO. That's entirely up to you.

Now, here's your code with all of those changes applied:

class String
  def shorten
    self.length > 100 ? "#{self[0..20]}. . .#{self[-20..-1]}" : self
  end
end

class Object
  def log_start
    puts <<-END.gsub(/^\s*\||#@.*$/, '')
      |  #{self.to_s.shorten}
    END
    self
  end

  def log(previous_method)
      puts <<-END.gsub(/^\s*\||#@.*$/, '')
        |   |
        |   |    #{previous_method}
        |   V
        |  #{self.to_s.shorten}
      END
    self
  end
end

Note: I didn't apply tip #11 because there are a bunch of ways to do it and I felt it would be better if I left it up to you how you want to do that.

To test it (Adapted to Ruby 2.2.2 but works the same):

class Integer
  def is_digits_pow_sum?(exp)
    self                           .log_start
        .to_s.chars.map(&:to_i)    .log("Get the digits")
        .map{|x| x**exp}           .log("Each digit to the power of #{exp}")
        .inject(&:+)               .log("Sum the digits")
        .equal?(self)              .log("Equals the start? (#{self})")
  end
end

441.is_digits_pow_sum?(3)

which prints

  441
   |
   |    Get the digits
   V
  [4, 4, 1]
   |
   |    Each digit to the power of 3
   V
  [64, 64, 1]
   |
   |    Sum the digits
   V
  129
   |
   |    Equals the start? (441)
   V
  false


The first thing I notice when looking at this code is the lack of documentation.

I would provide some more operators. Specifically I would go for operator< so type_id_t is usable as key for std::map and you should think about specializing std::hash so the class can be used with hash maps.

As the code is pretty short I don't find any more to say about it.

Btw.: Well done. I like this solution very much.


Using PHP explode() to parse multi-part error messages

A couple of thoughts:

This function is designed to only deal with a very sepcific use case - parsing a formatted error string.  For that reason I would recommend changing the function name to be more representative of what is actually happening.  Perhaps something like parseErrorString() or similar.
Since you are dealing with a very specific use case here, why would you require the caller to pass in the delimiters?  This function should fully encapsulate all the parsing logic.
Using an array for return, seems odd, particularly since you have spaces in your key names.  I would consider returning a stdClass or similar object with type, message, detail properties.
Though not strictly required, I would consider using regular expressions here, as I think that can clean things up as well as allow the solution to be less fragile to changes in the string format.
Using PHP_EOL as line break may be fragile. PHP_EOL is good for working with strings within same environment, but may fail if your application is running in a different environment than the environment your string is produced in.
Your function assumes happy path execution.  What if you get a poorly/unexpectedly formatted string?  Perhaps you are validating this string somewhere else, but if not, you should do it here in your function.

A refactoring, with these thoughts in mind, might yield something like the following:

function parseErrorString($string) {
    if(empty($string) || !is_string($string)) {
        throw new InvalidArgumentException('Non-zero length string expected');
    }
    $lines = preg_split('/\R/', $string);
    $error = array_reduce(
        $lines,
        function (&$err, $line) {
            $regex = '/^Error (Type|Message|Detail) - (.*)$/';
            $matches = [];
            $result = preg_match($regex, $line, $matches);
            if ($result !== 1) {
                // no match.  Is this an error condition?
                // at the very least, do nothing
                return $err;
            }
            $err->{strtolower($matches[1])} = $matches[2];
            return $err;
        },
        new stdClass();
    );
    return $error;
}


Check where the integers are Tprime or not

Change your algorithm

Currently, for each of \$10^5\$ numbers, you do a trial division loop that could check up to \$N/2\$ numbers, where \$N\$ can be as big as \$10^{12}\$.  This means that your program may require as many as \$10^{17}\$ operations.

You will certainly need to do better than that to finish within 2 seconds.

Proposal #1

The simplest way to speed up your program is to change your trial division loop.  I would make the following changes:

Check for divide by 2 as a special case before the loop.  In the loop, only check for division by odd numbers.
Make the loop go from small to large, as it is more likely that a random number will be divisible by a smaller number rather than a larger one.  In other words, start your loop at 3 and go up by 2 each loop.
Make the loop terminate at sqrt(n) instead of n/2.

Of the points above, #3 is the most important point.  This makes the trial division an \$O(\sqrt N)\$ operation instead of an \$O(N)\$ operation.  It reduces the max number of iterations from \$10^{12}\$ to \$10^6\$, making your total number of iterations in the worst case \$10^5 * 10^6 = 10^{11}\$.  So with this algorithm, the worst case probably wouldn't finish in 2 seconds, but the actual input might succeed.

Proposal #2

To make your program even faster, I would suggest the following:

Use the sieve of Eratosthenes to find all prime numbers from 2 to 10^6.  You can leave the output of the sieve as an array of booleans, telling you which numbers are prime.
Read in the input numbers.  For each input number, determine if it is a perfect square.  If it is, look up the square root of the input number in the array of booleans.  If the square root is prime, then the input number is a "tprime".

Part 1, the sieving part, takes around \$O(N * \log \log N)\$ time, where \$N\$ is 10^6, which means around \$4.3 * 10^6\$ steps.

Part 2 takes \$O(N)\$ time, where \$N\$ is 10^5, so around \$10^5\$ steps.

So the total of both parts comes out to roughly \$4.4 * 10^6\$ steps, which is much faster than proposal #1, and would definitely finish in under 2 seconds no matter what the input contained.

Thanks to maaartinus for suggesting the \$O(1)\$ lookup.


Your Cache class cannot be lighter than it already is. The most you can do is, introduce generics to remove the redundant casting every time you are trying to fetch from user defaults.

However, I see a major problem with the implementation here:

Is Cache also a UserDefaultsManager? Do you see Cache as something that extends the functionalities of the UserDefaultsManager class, or does your Cache use the functionalities of the UserDefaultsManager? I feel that composition is the way to go here than inheritance. I'd refactor this code to something like this:

protocol CacheHandling {
    func value<T>(forKey: String) -> T?
    func set<T>(_ data: T?, forKey: String)
}

extension CacheHandling {
    func value<T>(forKey: String) -> T? {
        let userDefaults = UserDefaults.standard
        if let encoded = userDefaults.object(forKey: forKey) as? Data {
            return NSKeyedUnarchiver.unarchiveObject(with: encoded) as? T
        }
        return nil
    }

    func set<T>(_ data: T?, forKey: String) {
        let userDefaults = UserDefaults.standard
        let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: data as AnyObject)
        userDefaults.set(encodedData, forKey: forKey)

        if (!userDefaults.synchronize()) {
            NSLog("Failed sync UserDefaults?")
        }
    }
}

struct Cache : CacheHandling {
    var currentProfileID: Int? {
        get {
            return value(forKey: Constants.Cache.CurrentProfileID)
        }
        set {
            set(newValue, forKey: Constants.Cache.CurrentProfileID)
        }
    }

    var login: String? {
        get {
            return value(forKey: Constants.Cache.Login)
        }
        set {
            set(newValue, forKey: Constants.Cache.Login)
        }
    }
}


SQL structure to save coordinates for spigot plugin

One of the requirements is that the coordinates of the player are stored, when the message is sent, and that it is stored in a sql table, so that admins on multiple spigot servers can access them independently of where the message was sent originally.

Which raises questions about transactions and concurrent access.

CREATE TABLE IF NOT EXISTS Meldung (
    id INT AUTO_INCREMENT NOT NULL,
    UUID VARCHAR(64),
    NAME VARCHAR(64),
    MESSAGE TEXT,
    XCOORD INT,
    YCOORD INT,
    ZCOORD INT,
    ISREAD TINYINT(1),
    primary key(id));

Your table structure raises many questions. Let's start with the obvious that MySQL table names might or might not be case-sensitive, depending on whether it runs on a filesystem that is case-sensitive or not.
The second is, do you need all columns to be nullable?
Third, I believe that at least UUID and ISREAD should have an index assigned, but that depends on the use-case mostly.
    id INT AUTO_INCREMENT NOT NULL,

Why is the casing different to everything else?
    UUID VARCHAR(64),

That's a bad column name, what UUID? Of what? PLAYER_UUID oder rather PLAYER_ID would be a better choice.
    NAME VARCHAR(64),

Same here, name of what?
    XCOORD INT,
    YCOORD INT,
    ZCOORD INT,

Unless the database provides a fitting datatype, storing the single values of a vector is the best thing you can do. Do not give into the idea "I will store this as string and parse it later", that's going to bite you or someone else down the road.

What I'm missing in this table is a CREATED_AT and READ_AT datetime field. The later could even double as flag whether it was read or not, by having it nullable.
What I'd also rather do is have a separate Player table, which allows to not store the name multiple times:
CREATE TABLE Player (
    -- Note that I've skipped a column-name prefix here,
    -- as it is clear what is meant because of the table.
    UUID VARCHAR(64) PRIMARY KEY,
    NAME TEXT NOT NULL
)

CREATE TABLE Meldung (
    -- Primary Keys are not nullable by default.
    ID INT AUTO_INCREMENT PRIMARY KEY,
    PLAYER_UUID VARCHAR(64) FOREIGN KEY REFERENCES Player(UUID),
    MESSAGE TEXT NOT NULL,
    PLAYER_LOCATION_X INT NOT NULL,
    PLAYER_LOCATION_Y INT NOT NULL,
    PLAYER_LOCATION_Z INT NOT NULL,
    -- Could also be SENT_AT.
    CREATED_AT DATETIME NOT NULL DEFAULT NOW(),
    READ_AT DATETIME
)

On another note, I like to use lowercase SQL with all columns and table names uppercase, like this:
create table PLAYER (
    -- Note that I've skipped a column-name prefix here,
    -- as it is clear what is meant because of the table.
    UUID varchar(64) primary key,
    NAME text not null
)

create table MELDUNG (
    -- Primary Keys are not nullable by default.
    ID int auto_increment primary key,
    PLAYER_UUID varchar(64) foreign key references PLAYER(UUID),
    MESSAGE text not null,
    PLAYER_LOCATION_X int not null,
    PLAYER_LOCATION_Y int not null,
    PLAYER_LOCATION_Z int not null,
    CREATED_AT datetime not null default NOW(),
    READ_AT datetime
)

As it is quite easier to type, and anything that is upper-case can be easily identified as table or column. It also removes any of the ambiguity regarding case-sensitivity in MySQL.


Let's say that you are starting with a list containing five elements:

$$
\newcommand{ptr}[1]{\overset{\mathtt{#1}}{\longrightarrow}}
\mathtt{head} \ptr{} \fbox{first}  \ptr{next}
                     \fbox{second} \ptr{next}
                     \fbox{rest}   \ptr{next}
                     \fbox{of}     \ptr{next}
                     \fbox{list}   \ptr{next} \mathtt{null}
$$

Then, you add a non-duplicate item called "another".  After executing head.next=newNode:

$$
% "align" allows us to do vertical alignment
% "\\" separates lines
% "&" is an alignment marker. The markers in different rows
% are positioned above each other, and horizontally centered.
\newcommand{ptr}[1]{\overset{\mathtt{#1}}{\longrightarrow}}
\begin{align*}
                                             &\mathtt{newNode} \\
                                             &\quad\downarrow  \\
\mathtt{head} \ptr{} \fbox{first} \ptr{next} &\fbox{another} \ptr{next} \mathtt{null} \\
                                             &\fbox{second}  \ptr{next}
                                              \fbox{rest}    \ptr{next}
                                              \fbox{of}      \ptr{next}
                                              \fbox{list}    \ptr{next}
                                              \mathtt{null}
\end{align*}
$$

You've just orphaned and discarded everything starting from the second element.  Then it gets worse when you set head=newNode.


Compare two sheets and copy new and delete duplicates in excel

I think you should be having performance issues because you have this:

   'Cycle through all the cells in that column:
   For iRow = 2 To iRowL
   'Call subRemoveNotRequiredR...

So you're going top to bottom and every time you go down and delete a row everything needs to shift up and recalculate and whatever. Go bottom up:

Print iRowL
       'Cycle through all the cells in that column:
       For iRow = iRowL to 2 step -1
       'Call subRemoveNotRequiredRows(TempData, SaleSamples)


Scripts loading Scripts Dynamically in Lua

On the first line, Card = {} should be local Card = {}, otherwise Card becomes a global, breaking encapsulation. You might want to consider using strict.lua or another method of "locking" the global table to prevent mistakes like this.

Having Card double as the metatable for card instances is pretty unusual. It will work, but now Card and each of its instances are polluted with an __index property, and this could be avoided simply by writing setmetatable({}, { __index = Card }) instead of setmetatable({}, Card), which is probably what people would expect to see anyway.

You declare the function as Card:new; it has an implicit self argument because of the colon. But you never use that argument; instead, you shadow it with a local variable named self. You probably wanted to do something like local instance = setmetatable({}, self), although as mentioned it would probably be better not to have Card double as the metatable for instances, so instead you could use local instance = setmetatable({}, { __index = self }).

local Card = {}

function Card:new(cardSuit, cardType, cardId)
    local instance = setmetatable({}, { __index = self })

    instance.id = cardId
    instance.type = cardType

    -- ...

    return instance
end

return Card

The same things apply to your second block of code.


Preprocessing Markdown Documents for Keywords

A few minor nit-picks:

I'd change the id checking code around a bit to avoid some redundant checks by first sanitizing the input:

id = string.IsNullOrEmpty(id) ? DefaultDocPage : id;
ViewBag.HomeLinkPage = id == DefaultDocPage ? string.Empty : DefaultDocPage;

Consider making DefaultDocPage a configurable property so you don't have to change the code if when someone asks to have a different name
Trim takes a params array so there is no need to do the ToCharArray, you can just pass in all the trim characters directly like this:

id.Trim('/')

Replacing

var filePath = Server.MapPath(Url.Content("~/Content/Documentation/" + id.Trim("/".ToCharArray()) + ".md"));

with string.format makes it a bit easier to read:

var filePath = Server.MapPath(Url.Content(string.format("~/Content/Documentation/{0}.md", id.Trim('/'))));

1. There is no need to cast to object here:

return View("Index", (object)contents.ToString());


Simulate only the result
A common problem in learning to program is over complicating the code. Complicated code is longer, harder to understand, and more prone to bugs. When the app is large even tiny over complications can lead to thousands of unneeded lines that must be tested and debugged.
All that matters is what comes out the other end of a function, how that is done does not matter.
Your code is way too complicated for what it needs to do. At its most simplest Rock paper scissors can be one line...
(["Tie ","P1 WINS with ","P2 WINS with "])[Math.random()*3|0]+ ((["Rock","Paper","Scissors"])[Math.random()*3|0])
Rewrite
The object rps is equivalent to yours. Calling rps.play() returns the same results, and is statistically identical to your results
const rps = (() => {
    const rand3 = () => Math.random() * 3 | 0;
    const plays = [
        () => "rematch",
        () => ({"1": rand3() + 1}),
        () => ({"2": rand3() + 1})
    ];
    return { play() { return plays[rand3()]() } };
})();

You do not need to simulate the game mechanics, just the game results.
There are 9 possible results.

1/3rd are draws,
1/3rd player 1 wins and
1/3rd player 2 wins.

When a player wins there is a 1 in 3 chance for any move type.
Thus a result first picks a random winner or draw, if there is a winner assign that player a random hand. There is no need calculate the hand the winner beats as that is inferred by the result.
Example 2
The following example produces a more readable result as an Example

const rps = (() => {
    const moves = ["Rock", "Paper", "Scissors"];
    const rand = (range = 3) => Math.random() * range | 0;
    const win = (m = rand()) => `Player ${rand(2) + 1} ${moves[m]} beats ${moves[(m + 2) % 3]}`;
    const plays = [win, win, (m = moves[rand()]) => `${m} draws with ${m}`];
    return { play() { return plays[rand()]() } };
})();

var games = 20;
while (games --) { log(rps.play()) }

function log(textContent) {
    info.appendChild(Object.assign(document.createElement("div"),{textContent}));
}