Connection Pool in Java 8 using Strategy and Factory Pattern

I'm not exactly an expert in this field so perhaps someone else can provide a more in depth answer but here are my initial thoughts about this code:

  public void forfeit(JdbConnection jdbConnection) throws ConnectionPoolException {

Why do you need to burden the user with that exception? If the connection was already returned or forcibly taken, does the user of this method really care?
I would just silently check if that is the case and ignore the call if it is.

thread safety?

Let's say we have a pool with only 1 connection left. What happens if 2 threads call the borrow()?

Thread one checks if (pool.size() > 0) { and it passes. But now thread one is paused and thread two get's to run.

Thread two also checks if (pool.size() > 0) { and it also passes.

Who will get the connection from the pool after this point?

It can actually get even worse. What if we not only have one connection available in the pool, but there's also an expired one.

Both threads should be able to get a connection right? But both went inside the if block. So 1 gets the connection, the other get's nothing.

The else part isn't executed for either of the threads.

Looking at the javadoc for ConcurrentLinkedQueue I don't think your code even works at the moment.

pool.remove() does not exist. pool.remove(Object obj) does but that returns a boolean to tell if removing the obj succeeded or not.

What you want is problably pool.poll().

How do you decide a good lease time? Sometimes a querry takes a couple of minutes to run. These are fine if you don't run them often. But if the lease time is set too low the query will never be able to finish. (Even tho the use case of that query could be a valid one).

Does factory.create() already set up an actual connection with the database? What if I set up a pool with 20 possible connections but actually only use a single connection for a couple of hours. Do I use up 20 connections with the database?

Why not create a new connection the moment one is asked (if we didn't pass the connection limit yet)?

What should I do if I didn't get a connection? (error no connection available). Should I run an active loop until I eventually get my connection?

You probably want to provide a method that puts the request into a queue (perhaps with a timeout) and gives the first available connection to the first in the queue. This way if too many threads are asking for a connection at once, they'll all eventually get their connection instead of overloading the system with busy-waiting-resource-wasting threads.

Multithreaded solutions are always tricky to get right. In general it's often better to try to search for an existing solution. Since I don't have experience in this field I can't really recommend any specific ones though...


Java enum-based factory to calculate entry parameters

Your implementation is good, but I would suggest following points to improve:

It is really hard to test/mock source2ToCheck.getSource().
Source2 contains a lot logic/functionality (it is source type and
factory) it has to be simplified.
getSource() creates new course
object it is confusing
getSource(...) calls getAction(...) that create a source object. It is wired.
Be aware source2Class.newInstance() is deprecated since java 9
source2Class.getDeclaredConstructor().newInstance()

Suggestions:

I would propose to create dedicated interface/class for source factory
Rename Source2 to SourceType.
Throw custom exception CustomCantCreateSourceException instead of return new SourceUnkown(). Because it is real exceptional situation.
Remove public methods modifier from Source interface
Minor enhancements you can find in following code

Source Factory interface:

public interface SourceFactory {
    Source create(SourceType type);
}

Factory implementation:

public class SourceFactoryImpl implements SourceFactory {
    @Override
    public Source create(SourceType type) {
            try {
                return type.getClazz().getDeclaredConstructor().newInstance();
            } catch (InstantiationException | IllegalAccessException
                    | NoSuchMethodException | InvocationTargetException e) {
                SENSITIVE_LOGGER.warn("<< Exception occured during init of {}, returning unkown source.", source2Class);
                throw new CustomCantCreateSourceException();
            }
    }
}

Renamed Source2:

public enum SourceType {

    IB("IB", SourceIb.class),
    CCWEW("BOT", SourceCcwew.class),
    OBD("CUF", SourceCuf.class),
    PB("PB", SourcePb.class),
    COK("COK", SourceCok.class),
    CCZEW("CCZ", SourceCczew.class),
    CRM("CRM", SourceCrm.class),
    APP("APP", SourceApp.class);

    private static final Logger SENSITIVE_LOGGER = SensitiveLoggerFactory.getSensitiveLogger(SourceType.class);

    private String configChannel;

    private Class<? extends Source> clazz;

    private SourceType(String configChannel, Class<? extends Source> clazz) {
        this.configChannel = configChannel;
        this.clazz = clazz;
    }

    public Class<? extends Source> getClazz() {
        return clazz;
    }

    public String getConfigChannel() {
        return configChannel;
    }
}

Usage:

public class SourceService {
    private final SourceFactory factory;

    public SourceService(SourceFactory factory) {
        this.factory = factory;
    }

    public EnumSet<SourceType> fillSources() {
        final SourceCalculationData data = new SourceCalculationData();

        final EnumSet<SourceType> presentSources = EnumSet.noneOf(SourceType.class);
        for (final SourceType source2ToCheck : SourceType.values()) {
            if (factory.create(source2ToCheck).isPresent(data)) {
                presentSources.add(source2ToCheck);
            }
        }
        return presentSources;
    }
}


Clubbing three queries that return mutually exclusive records

You can use aggregation like this:

select "Key",
   MAX(CASE WHEN "Is_Orig" = 1 THEN "Value" END) "Orig Value",
   MAX(CASE WHEN "Is_Prev" = 1 THEN "Value" END) "Prev Value",
   MAX(CASE WHEN "Is_Curr" = 1 THEN "Value" END) "Curr Value"
from statistics
group by "Key"

The CASE statements select the value in each case and return NULL in the other cases. MAX is just to get that one value from the nulls.

Have a look at https://modern-sql.com/use-case/pivot for some background. It also refers to an Oracle specific feature called "modeling" that allows a similar thing.


Solution to knapsack problem exceeds time and RAM limits

Part of the reason you're running out of memory is that you are allocating all of your items into memory twice. Once in the two lists weights and values, and once again in hash_table.

Looking at your program, I don't see a need for you to keep your weights and values allocated as you do. You iterate through them one at a time in your outer for loop. What I'd do is make use of a generator and wrap the file reading in a function:

def read_file():
    with open('knapsack.txt') as fh:

        # these value names are a bit more descriptive, and
        # you can use a next() call on this generator
        # to extract these values
        WEIGHT, SIZE = map(int, next(fh).strip().split())
        yield WEIGHT, SIZE

        for line in fh:
            yield map(int, line.strip().split())

This way you can do tuple unpacking in a for loop:

iterator = read_file()
# here's that next call I mentioned
WEIGHT, SIZE = next(iterator)

# iterate over the remaining values
for weight, value in iterator:
    # do something

This will keep copies of your values from proliferating throughout the execution of your program when you really don't need them.

I'd also look into enumerate, since you need the index for part of your hash_table keys, but you also need the weight and value as well. This eliminate repeated lookups that slow down your code:

for i, (w, v) in enumerate(read_file(), start=1):
    for x in range(WEIGHT + 1):
        ...

To show the effect:

# repeated index lookup
python -m timeit -s 'x = list(range(1, 10000))' 'for i in range(len(x)): a = x[i] + 2'
500 loops, best of 5: 792 usec per loop

# no repeated index lookup
python -m timeit -s 'x = list(range(1, 10000))' 'for i, j in enumerate(x): a = j + 2'
500 loops, best of 5: 536 usec per loop

It doesn't appear that you really need the leading 0 0 row on weights and columns, either, since you start the index at 1, skipping it. Avoiding the addition of lists here cuts down on overhead, and you can specify enumerate to start at a given value with the start kwarg as I've done above.

The goal here should be to iterate over a collection as little as possible, so a refactored version might look like:

def read_file():
    with open('knapsack.txt') as fh:

        # these value names are a bit more descriptive, and
        # you can use a next() call on this generator
        # to extract these values
        WEIGHT, SIZE = map(int, next(fh).strip().split())
        yield WEIGHT, SIZE

        for line in fh:
            yield map(int, line.strip().split())

iterator = read_file()
WEIGHT, SIZE = next(iterator)
hash_table = {(0, i): 0 for i in range(WEIGHT + 1)}

for i, (w, v) in enumerate(iterator, start=1):
    for j in range(WEIGHT + 1):
        if w > j:
            hash_table[(i, j)] = hash_table[(i - 1, j)]
        else:
            hash_table[(i, j)] = max(
                hash_table[(i - 1, j)],
                hash_table[(i - 1, j - w)] + v
            )

This doesn't avoid all of the memory issues, however. You are dealing with a relatively large file and housing that in a dictionary will lead to heavy memory usage. As noted in the Wikipedia article, the solution you have implemented will have a worst-case space complexity of O(nW), which for this file is approximately O(n * 2000000)


Toggling only a single class as active in a list with vanilla JS or CSS

Another approach could be with hidden radio inputs and :checked CSS selector :

input { display: none }
input:checked ~ * { color: red }
<input type="radio" name="li" checked>
1

<input type="radio" name="li">
2

<input type="radio" name="li">
3

<input type="radio" name="li">
4


Event handlers & helper methods for a Kendo Grid

The second solution has two main improvements:

Fewer lookups. Every time you call your original getSelectedId method,
the lookup for $("MainGrid").data("kendoGrid"); is performed again.
The 2nd version caches this in gridHandler.mainGrid -- only one lookup.
The same goes for subGrid.
More compact. For example the subGrid local variable here was not particularly useful:

function hideSubGrid() {
    var subGrid = $("SubGrid").data("kendoGrid");

    subGrid.addClass("hidden");
}

It would have been simpler and more natural this way:

function hideSubGrid() {
    $("SubGrid").data("kendoGrid").addClass("hidden");
}

Reduced namespace clutter. By putting the methods in a gridHandler, you don't have many methods lying around in the global namespace, they are all neatly inside gridHandler.


This is a very straightforward implementation which is great for maintainability and readability. Here are some things you could improve:

Not All Comparisons Work In Obvious Ways

As mentioned in the comments by Jerry Coffin and Loki Astari, you may run into issues with floating point values or values which may not be padded how you think, or for which the padding contains random values. You could solve this by also passing in a pointer to a comparison function and calling that function to do the comparison.

Naming

Your naming could be improved a little. The function is named dubCount(), but from the comments and the name of the return value it should probably be conflictCount() or at least dupeCount(). It's not clear what dub refers to in dubCount() (at least to me). Also the parameter name a tells me nothing, and since it's a pointer to void, I have no contextual clue, either. I'd rename it to something like items and rename the items parameter to numberOfItems or numItems, and rename size to itemSize or sizePerItem or bytesPerItem so that it's more clear just from the function prototype what the parameters mean.

Use const where appropriate

In this function, none of the parameters to the function are modified. When your function doesn't modify a parameter, it should be marked as const. This lets both the compiler and a reader know the function won't change those values. The compiler may be able to make some optimizations with that info, and a reader can do more reasoning about the function without reading its actual code, which is helpful.

Performance

You noted that the algorithm you're using is \$\mathcal{O}(n^2)\$. If you sorted the items in the array first, you could use an O(n) search on the result as you'd be able to simply run through the array until you hit a different value. (Note that this may depend on the statistical nature of your input data and the sort algorithm you use. But in general, I'd expect to see a speedup in such a case.) Most fast sort algorithms are \$\mathcal{O}(n * log(n))\$ so the result would be \$\mathcal{O}(n + n * log(n))\$ (I think? Check my math). Note that you would use the same comparison function for the sort as you would for checking for duplicates.


HackerEarth Challenge Find Maximum Taste of Fruits

You are searching over the full set of permutations, which leads to a time complexity of \$O(n!)\$, which is rarely a good thing. This seems like the type of problem that would benefit from a dynamic programming approach. I don't find it entirely satisfactory, as it uses a top-down approach, but it is much more efficient than your implementation, so here it goes:

The basic idea is that, if you take a subset \$A\$ of \$m\$ items, and compute the \$m\$ values \$t_{A,j}\$, being the "best taste using the items in \$A\$ and ending in the \$j\$-th item, you can compute \$t_{A^*, m+1}\$, where \$A^*\$ is the set \$A\$ augmented with an extra item not in that set, easily. This is kind of confusing, I know, but below I am indexing memoized solutions by (items_remaining_to_be_used, last_item_used), and building the total taste by adding one of the remaining items at a time. It may be easier to look at the code:

def top_down(seq):
    memo = {}
    for idx, item in enumerate(seq):
        key = (frozenset(seq[:idx] + seq[idx+1:]), item)
        memo[key] = 0
    mult = 1
    best_taste = None
    while best_taste is None:
        mult += 1
        new_memo = {}
        for (items, last), taste in memo.items():
            items = list(items)
            for idx, item in enumerate(items):
                new_taste = taste + mult * abs(item - last)
                new_set = frozenset(items[:idx] + items[idx+1:])
                if not new_set:
                    best_taste = max(new_taste,
                                     0 if best_taste is None else best_taste)
                else:
                    new_key = new_set, item
                    new_memo[new_key] = max(new_memo.get(new_key, 0),
                                            new_taste)
        memo = new_memo
    return best_taste

Comparing to a function implementing your naive approach:

def naive(seq):
    best_taste = 0
    for perm in permutations(seq):
        taste = 0
        for idx, (this, that) in enumerate(zip(perm[:-1], perm[1:])):
            taste += (idx + 2) * abs(this - that)
        best_taste = max(best_taste, taste)
    return best_taste

The timing differences start out small:

a = [random.randint(100) for _ in range(5)]
%timeit naive(a)
1000 loops, best of 3: 215 µs per loop
%timeit top_down(a)
1000 loops, best of 3: 262 µs per loop

But things soon favor the top_down implementation massively:

a = [random.randint(100) for _ in range(10)]
%timeit naive(a)
1 loops, best of 3: 10.4 s per loop
%timeit top_down(a)
10 loops, best of 3: 44.6 ms per loop

That's over a 200x improvement! And of course:

>>> naive(a) == top_down(a)
True

And even the largest problem in your challenge can be solved in a reasonable amount of time, not sure if it will be fast enough though:

a = [random.randint(100) for _ in range(15)]
%timeit top_down(a)
1 loops, best of 3: 3.76 s per loop


You definitely want to document those interfaces.
WarehouseClient should probably not be a static class.
The name of the NextSession event in IWarehouse doesn't really mean anything to me. Just from reading the interface I don't really know when this event would be raised. Maybe NextSessionCreated or NextSessionOpened?
CurrentSession would be a better name instead of Session.
Also it is not clear if the Session can get opened and closed multiple times. If a session can't be opened and closed multiple time then maybe use Start and Finalize instead? Those imply (at least to me) more of a once only action.
In IDeposit: ItemWithdrawed should be ItemWithdrawn
I'm not 100% sure about the ITerminal and IDeposit relation. The way I read is that a client can deposit an object into a terminal which will then give him some kind of reference to that transaction in form of an IDeposit. Now IDeposit also has a Withdraw() method but it's not clear what the semantics of that is. Can the client who deposited the item basically withdraw that deposit? Or is it mean to be withdrawn by someone else - if yes then shouldn't there be a Withdraw() method on the terminal rather than on the deposit? It's probably not clear to me because I don't know what the workflow is supposed to be but it's hard to deduce from just the interfaces alone.

All that being said I'd say: Yes you want that backend API. Apparently the whole system expects a certain kind of workflow and providing a structure which an implementer can fill in will make it much easier for them and probably reduce bugs.


First of all, absurd terseness does not imply lightning speed. Quite the contrary, it makes understanding and thus optimizing that much more difficult.

So, get some useful names.

Anyway, if you want to go for reasonable brevity, or just remove some confusion, remove all the unused typedefs. And then remove the rest of them too, as they also have negative value.

Now, a tip for getting a stunning performance-boost:
Stop copying things, especially if doing so needs dynamic allocation.
That means lcp() should receive its arguments by constant reference.

Next, hopefully your compiler hoists min(b.size(), a.size()) out of the loop. Still, do you really want to rely on that?

Are you sure you need all the headers, and want to live with the unportability?
Read "Why should I not #include <bits/stdc++.h>?".

And also, don't pollute the global namespace with all kinds of things, which you are unlikely to know for now, let alone the future.
See Why is “using namespace std” considered bad practice? for more elaboration on that.


Creating SQL queries for a MySQL database

Assuming you're protecting yourself from SQL Injection and the like, there are just a couple things that stand out to me:

It doesn't seem clear to me why the closing parenthesis for your primary key constraint is in the create_ct_query2() function rather than in the primary_key_constraint() function.
I believe the code would be far easier to read, test, and extend if it were built using objects rather than global functions.
Since you are new to PHP, I think it is worth mentioning that single quotes and double quotes are treated differently.  Knowing this, as a personal preference, I tend to use single quotes unless I intentionally need / want to use the added functionality of double quotes.
While related to refactoring, I believe my other suggestions start to delve more in to the readability of things like create_ct_query().  This starts to feel a bit nit-picky, and almost a matter of style.  For example, with create_ct_query(), it took me a minute to realize what "ct" meant.  Only after looking inside the function and seeing the string being created did I realize what it did.  I feel that something like "get_create_table_query()" or similar would be a bit more intuitive.

Regarding documentation, I have found Eclipse and other tools to utilize the following style of doc-blocks.  The @return is especially useful for code-completion of methods available on the returning object in my IDE.  Documentation tools tend to have built-in support for other tags like @author as well.

/**
 * Description of someMethod()
 *
 * @param int $someInt
 * @param ObjectName $someObj
 * @return AnotherObj
 */
public function someMethod($someInt, ObjectName $someObj)
{
    // ...

    return new AnotherObj();
}


Its not thread safe!

Looks like you can still create instances manually (though you would have to derive a class that can use the protected constructor) or copy the one created by getInstance().

Why not use the classic Singleton pattern?

class ImGUIManager
{
     public:
         static ImGUIManager& getInstance()
         {
             static ImGUIManager instance;   // static member
                                             // Correctly constructed on first use.
                                             // Will be deleted on exit.
             return instance;
         }
         // PUT YOUR INTERFACE HERE

     private:
         ImGUIManager(){} // Make sure the constructor is private.
         // Delete the copy and move constructors.
         ImGUIManager(ImGUIManager const&)            = delete;
         ImGUIManager& operator=(ImGUIManager const&) = delete;
         ImGUIManager(ImGUIManager&&)                 = delete;
         ImGUIManager& operator=(ImGUIManager&&)      = delete;
};

Some References:

C++ Singleton design pattern


You have the right approach of creating two separate forms for your two models involved (User and PlayerProfile) but I think the formset is overkill and not the right tool for the job anyway.

I’d rather create the ModelForms more naturally:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'password')

class PlayerProfileForm(forms.ModelForm):
    class Meta:
        model = PlayerProfile
        fields = ('balance',)

And glue them together with an ad-hoc "form" along the lines of:

class PlayerUserForm:
    def __init__(self, *args, **kwargs):
        self.user_form = UserForm(*args, **kwargs)
        self.player_form = PlayerProfileForm(*args, **kwargs)

    def is_valid(self):
        # Make sure to **not** short-circuit so as
        # to populate both forms errors, if any.
        user_valid = self.user_form.is_valid()
        player_valid = self.player_form.is_valid()
        return user_valid and player_valid

    @transaction.atomic
    def save(self):
        user = self.user_form.save()
        player = self.player_form.save(commit=False)
        player.user = user
        player.save()
        return player

And you can add template helpers for good measure:

    def __str__(self):
        return self.as_table()

    def as_table(self):
        return mark_safe(f'{self.user_form.as_table()}\n{self.player_form.as_table()}')

    def as_ul(self):
        return mark_safe(f'{self.user_form.as_ul()}\n{self.player_form.as_ul()}')

    def as_p(self):
        return mark_safe(f'{self.user_form.as_p()}\n{self.player_form.as_p()}')

This is untested but should work as a drop-in replacement for your PlayerUserForm.


Checking if the site resolve a DNS or not

You are doing way more than necessary, if all you want to verify is that the hostname resolves to an IP address.

gethostbyname() comes pretty close to doing the job:

  Returns the IPv4 address or a string containing the unmodified hostname on failure.

Actually, that's annoying.  Try gethostbynamel() instead:

  Returns an array of IPv4 addresses or FALSE if hostname could not be resolved.

So, you could just do

$url_parts = parse_url($url);
return gethostbynamel($url_parts['host']) ? true : false;

Note, however, that the gethostbyname() family of functions relies on the operating system to do the name resolution in whatever way it is configured.  Usually, that means using DNS.  However, it might also use a local hosts file, NIS, LDAP, Multicast DNS, etc.  dns_get_record() would actually perform a DNS lookup, independent of the machine's preferred name resolution mechanism.  If you want to go that route, then it looks like checkdnsrr($host, 'A') would be convenient.

The distinction is almost always inconsequential, but I thought I'd mention it since you specifically mentioned DNS resolution in your question.


Some preliminary notes for now (I'll add later):

Whenever you need to write (if n n 2) or (if (not n) 2 n), you can instead write (or n 2). or will take any number of arguments and return either nil or the first argument that evaluates to non-nil.

When working with optional arguments, you can set defaults for them.

(defun place-value-to-integer (the-list &OPTIONAL place-value)
  (let ((place-value (if place-value place-value 1)))
  ...

can be written as

(defun place-value-to-integer (the-list &OPTIONAL (place-value 1))
  ...

I don't have time to get into the rest right now, but you're using loop to setf a series of hash values, which tells me you could probably simplify it by using a more functional approach (it might be one of the exceptions, but it doesn't feel like one at first glance).

EDIT:

(if a b nil) is equivalent to (when a b) (and it's good style to use the second over the first).

EDIT2: Ok, wow, hey. That's two hours of my life I won't get back. I wrote up and edited down a pretty ridiculously long piece on my process (if you care, it's here). Here's how I would tackle a brute-force approach to this problem.

EDIT3: Simplified slightly.

(defpackage :cry-fun (:use :cl :cl-ppcre))
(in-package :cry-fun)

(defun digits->number! (&rest digits)
  (apply #'+ (loop for d in (nreverse digits) for i from 0
                   collect (* d (expt 10 i)))))

(defun number->digits (num &optional (pad-to 5))
  (let ((temp num)
        (digits nil))
     (loop do (multiple-value-call
                   (lambda (rest d) (setf temp rest digits (cons d digits)))
                (floor temp 10))
           until (= pad-to (length digits)))
     digits))

(defun string->terms (problem-string)
  (reverse
   (mapcar (lambda (s) (mapcar (lambda (i) (intern (format nil "~a" i)))
                   (coerce s 'list)))
           (split " " (string-downcase problem-string)))))

(defmacro solve-for (problem-string)
  (let* ((arg-count (length (remove-duplicates (regex-replace-all " " problem-string ""))))
         (nines (apply #'digits->number! (make-list arg-count :initial-element 9))))
    `(loop for i from 0 to ,nines
           when (apply (solution-fn ,problem-string) (number->digits i ,arg-count))
           collect it)))

(defmacro solution-fn (problem-string)
  (let* ((terms (string->terms problem-string))
         (args (remove-duplicates (apply #'append terms))))
    `(lambda ,args
       (when (= (+ ,@(loop for term in (cdr terms) collect `(digits->number! ,@term)))
                (digits->number! ,@(car terms)))
             (list ,@(mapcan (lambda (i) (list (symbol-name i) i)) args))))))

EDIT (by jaresty): adding comments to show example intermediate values for "solution-fn"

(defmacro solution-fn (problem-string)
  (let* ((terms (string->terms problem-string))
     ;example: (terms ((o k) (i t) (i s)))
         (args (remove-duplicates (apply #'append terms))))
         ;example: (args (o k t i s))
    `(lambda ,args
       (when (= (+ ,@(loop for term in (cdr terms) collect `(digits->number! ,@term)))
                (digits->number! ,@(car terms)))
        ;example: (when (= (+ (i t) (i s)) (o k)
             (list ,@(mapcan (lambda (i) (list (symbol-name i) i)) args))))))
        ;example: (list "o" o "k" k "t" t "i" i "s" s)


Rendering and re-rendering a Mustache template

I don't think this will cause you any problems; it may offer superior performance in many scenarios, especially over re-rendering the template. The only other option that comes to mind is to keep this invisibly in the DOM somewhere and use JQuery's clone() to re-render it as needed. I use this latter technique especially if the original template is pre-rendered from another source. Just bear in mind that if you do use clone() JQuery also clones element IDs if you have any, which may cause your selectors on those IDs to behave unexpectedly if you don't change them after the clone (or refactor the source template).


Check if a file exists in a directory or parent

It's safer to use the Path.Combine method for joining the directory name and file name:

var fileName = @"c:\temp\foo.txt";

var fileExists =
    File.Exists(fileName) ||
    File.Exists(
        Path.Combine(
            Directory.GetParent(Path.GetDirectoryName(fileName)).FullName,
            Path.GetFileName(fileName)
        )
    );

What else you could to is to take it out of the if and use a helper variable and add some identation.

Another approach could be to encapsulate the search paths and the file exists check:

static IEnumerable<string> GetFileSearchPaths(string fileName)
{
    yield return fileName;
    yield return Path.Combine(
        Directory.GetParent(Path.GetDirectoryName(fileName)).FullName,
        Path.GetFileName(fileName)
    );
}

// or as an extension
static bool FileExists(string fileName)
{
    return GetFileSearchPaths(fileName).Any(File.Exists);
}

Usage:

if(FileExists(fileName)) ...

or you can get the actual file name from the search:

static string FindFile(this string fileName)
{
    return GetFileSearchPaths(fileName).FirstOrDefault(x => File.Exists(x));
}

var actualFileName = FindFile(fileName);

if (!string.IsNullOrEmpty(actualFileName)) ...


Readability

Your conditional checks are very very long. They run off the screen. At the very least, add some new lines:

else if ((month == 9 && day >= 16 && day <= 30) ||
         (month == 10 && day >=1 && day <= 31) ||
         (month == 11 && day >= 1 && day <= 30) ||
         (month == 12 && day >=1 && day <=15))

But this still makes it very hard to actually understand what is going on. There's no really any notion of "range" in this code. You are simply hardcoding each individual month separately.

Ranges

Representing the range "3/16 to 6/15" is difficult. Representing the range 316 to 615 is easy. If we don't care about checking for invalid dates, we can uniquely represent the year by doing month * 100 + day and looking at it that way.

int month_day = month * 100 + day;
if (month_day <= 315) {
    System.out.println("Winter");
}
else if (month_day <= 615) {
    System.out.println("Spring");
}
else if (month_day <= 915) {
    System.out.println("Summer");
}
else if (month_day <= 1215) {
    System.out.println("Fall");
}
else {
    System.out.println("Winter");
}

By treating the ranges as one-sided, it's easy to organize the code to actually look like we're looking for ranges. Winter simply appears on both ends for simplicity.


Tested on firefox browser, Chrome could not support default argument syntax

I think it's good to write code that runs anywhere.
You can make this code run anywhere with a simple modification:

Rename findMaxSequence to findMaxSequenceInner and remove the default values
Create a new findMaxSequence function

Like this:

function findMaxSequence(array) {
    return findMaxSequenceInner(array, -1, -1, 0, []);
}

function findMaxSequenceInner(array, start, end, i, results){
    // ...
}

Instead of this:

if((array.length == 1) || (array.length == 0)){

It would be better to combine those conditions:

if (array.length <= 1) {

When all branches of if-else-if-else conditions return, you can simplify to multiple ifs, like this:

function findMaxSequenceInner(array, start, end, i, results){
    if (array.length <= 1) {
        return "[ " + array + " ]";
    }
    if (i >= array.length - 1) {
        if (start != -1) {
            results.push(array.slice(start, end+1));
        }
        if (results.length > 0) {
            results.sort(
                function(a, b) {
                    return a.length < b.length;
                }
            );
            return "[ " + results[0].toString() + " ]";
        } else {
            return "no";
        }
    }
    if (array[i] < array[i+1]) {
        if (start == -1) {
            start = i;
        }
        return findMaxSequenceInner(array, start, i+1, ++i, results);
    }
    if (array[i] >= array[i+1]) {
        if (start != end) {
            results.push(array.slice(start, end+1))
        }
        return findMaxSequenceInner(array, -1, -1, ++i, results);
    }
}

Looking at this part:

if (array[i] < array[i+1]) {
    if (start == -1) {
        start = i;
    }
    return findMaxSequenceInner(array, start, i+1, ++i, results);
}
if (array[i] >= array[i+1]) {
    if (start != end) {
        results.push(array.slice(start, end+1))
    }
    return findMaxSequenceInner(array, -1, -1, ++i, results);
}

Notice that the two conditions perfectly complement each other.
So you can remove the second condition completely, as it will always be true if the first one was false:

if (array[i] < array[i+1]) {
    if (start == -1) {
        start = i;
    }
    return findMaxSequenceInner(array, start, i+1, ++i, results);
}
if (start != end) {
    results.push(array.slice(start, end+1))
}
return findMaxSequenceInner(array, -1, -1, ++i, results);

Once again, nesting level is reduced, which is easier to read.

Lastly, there are some formatting issues:

The indentation is inconsistent
The spacing is too tight, for example }else if(array[i] >= array[i+1]){ is easier to read as } else if (array[i] >= array[i+1]) {, that is, spaces inserted around braces

In the above examples I already adjusted the indenting and spacing, I hope you see the difference from your original.


Go function to test whether a file exists

Instead of checking with an if statement if errStat is null and then returning false:

if errStat != nil {
    return false
}
return true

you can return a Boolean expression:

return errStat == nil


Selectively printing elements on web page using a bookmarklet

Declare variables before using them - your node variable is never declared. Use let node = instead.
Typo? node.classList.remove.(t_class) should be node.classList.remove(t_class);
Variable casing The vast majority of professional JavaScript uses camelCase for most variables, including parameters. There are a few exceptions (like ALL_CAPS for things like constant magic numbers, and PascalCase for constructors and namespaces).
Variable names It's not entirely clear on the initial encounter of removeClass what the parameters mean. Maybe change:

t_selector -> selectorToShow
t_class -> hiddenClassName

or something similar.
Always use strict equality, avoid sloppy equality to avoid readers of the code having to understand coercion weirdness to be 100% confident of what the code is doing.
Semicolons Either use semicolons when appropriate, or (if you don't like them and you're an expert who can avoid the pitfalls of ASI) don't. To be stylistically consistent, choose one style and stick with it. Consider a linting rule.
Relying on a site's classes is unreliable, especially for sites that are being actively maintained and developed. Many of those who write bookmarks and userscripts are familiar with this issue. The site may change their CSS, resulting in d-print-none doing nothing. Bookmarklets and userscripts are prone to requiring updates when a site changes regardless - but reducing the chance of needing maintenance when a change occurs is good.
Whatever d-print-none does currently, I'd append another <style> tag that inserts your own class (or data attribute) that does the same thing, eg:
const style = document.body.appendChild(document.createElement('style'));
style.textContent = `
@media print
{
    .melted-bookmarklet-print-none, .melted-bookmarklet-print-none *
    {
        display: none !important;
    }
}
`;

Then toggle that class instead (and do style.remove() at the end if you want).
(You might be tempted to iterate through the elements and apply the style directly to elements, but that could break the site's built-in display properties if it happens to have styles already applied directly to elements.)
Or, you could use CSS alone instead of iterating through elements. How exactly to do this depends on where the app-flex-chart and app-flex-grid are located on the page, but it could look something like this, if they're both descendants of the <body>:
const style = document.body.appendChild(document.createElement('style'));
style.textContent = `
@media print
{
    body > *:not(app-flex-chart):not(app-flex-grid),
    body > *:not(app-flex-chart):not(app-flex-grid) * {
        display: none !important;
    }
}
`;

(feel free to engineer to be more flexible and less repetitive if you think it'd be helpful)
This way, all elements which are not the .app-flex-chart nor .app-flex-grid will be hidden, without any intermediate classes or element iteration.
Or save a reference to the two elements you want to print, remove everything, then append the two back:
const elms = ['app-flex-chart', 'app-flex-grid'].map(s => document.querySelector(s));
document.body.textContent = '';
for (const elm of elms) {
  document.body.appendChild(elm);
  // if needed to put them on separate lines:
  document.body.appendChild(document.createElement('div'));
}

That's the version I'd prefer, if feasible. You may have to insert intermediate elements for the page's styles to apply. (If that gets too complicated, use a different approach.) If you want the original page to remain interactable, you could open a new window which gets populated with the content of elms instead. (You'll also have to append <style> and CSS link tags from the original page)
Bookmarklet or userscript? You're currently using this as a bookmarklet. It depends how you're managing them, but if you aren't using a special utility for it, I think userscripts are more maintainable, due to a few factors:

Userscript editor interfaces are meant to be usable as code editors. In contrast, a bookmarklet, when installed, isn't very user-friendly to edit:

Userscripts can be saved in separate external files, rather than existing in the browser's internal ether.

Userscripts are more flexible in when they're run. Most importantly, they can run automatically without requiring a click. You may find this helpful.

If you want to try this out as a userscript, try Tampermonkey.
Depending on how you're using the printed page and how often you're printing, you can consider using Puppeteer in Node to scrape and print the elements completely automatically.


Here are some comments on your code:

I assume the structure of the input data is to be taken as it is: one long list where only the 1 out of 8 values contribute to the output.
c = 0 is defined but never used
It is not recommended to use compound statements (see PEP8 - "Other Recommendations"): use a separate line for an if and the statement under condition.
/ performs a true division (giving a float). To avoid switching between float and int, use integer division: //
if i == 512: break could me omitted if you would limit the range of the for loop immediately. Instead of len(data) use min(512*16, len(data))
The multiplication i * 16 can be avoided if you use the step argument of range() so that i takes multiples of 16.
Instead of "%04x " % d use the newer f-strings
Instead of calculating d, you could just pass high and low to the string template and format each independently.
Instead of if (i % 16) == 15: you could use a nested loop that deals with one output line
Your code produces a blank at the end of each line. That seems unnecessary. With " ".join you would not have this extra blank.
out has a terminating \n, but print also prints a newline as terminator (by default). With "\n".joinyou would not have this extra newline

Here is how it could look:

# Set a maximum to the output
length = min(512*16, len(data))

# Format data
lines = []
for line in range(0, length, 256):
    items = []
    for i in range(line, min(line+256, length), 16):
        items.append(f"{data[i+1]:02x}{data[i]:02x}")
    lines.append(" ".join(items))
out = "\n".join(lines)

# Output
print(out)

Here is how the above data formatting translates when using list comprehension. You can split the expression over multiple lines to improve readability:

# Format data
out = "\n".join([
            " ".join([
                f"{data[i+1]:02x}{data[i]:02x}"
                for i in range(line, min(line + 256, length), 16)
            ])
            for line in range(0, length, 256)
        ])


I don't know rabbit and have only small nit-picks regarding C++.

emplace

You might consider constructing threads in place instead of moving them to vector.

Instead of:

threads.push_back(std::thread(RabbitThread));

I would try:

threads.emplace_back(RabbitThread);

clear()

Is threads.clear(); in main() necessary?

struct and null pointer

This looks like C-style struct keyword usage. It is very rare to see in C++ (not saying it is wrong).

struct ev_loop *loop = ev_loop_new(0);

This might be also ok and looks more familiar

ev_loop *loop = ev_loop_new(0);

One more thing and this is a wild guess. Is this zero really a NULL pointer?

struct ev_loop *loop = ev_loop_new(0);

This would be more C++11 way:

struct ev_loop *loop = ev_loop_new(nullptr);

hardware_concurrency()

I really have no idea where lies bottleneck in you use case but I suspect it is not CPU bound so maybe you might utilize even much more threads.

int MaxThreads = std::thread::hardware_concurrency();


Javascript refactor if condition function

Basically we search for the most close number from array where our number belongs. After we find the min value, we take the index of it and add 1, because the rank starts from 1

//rank 1 : 150 - 500
//rank 2 : 500 - 1000
//rank 3 : 1000 - 2000
//rank 4 : 2000 - 3500
//rank 5 : 3500 - 5000
//rank 6 : 5000 - 5500

let pointsRank = [150, 500, 1000, 2000, 3500, 5000, 5500]

function rank(pointsRank, score) {
  var closest = pointsRank.reduce(function(prev, curr) {
    return (Math.abs(curr - score) < Math.abs(prev - score) ? curr : prev);
  });
  var rank = pointsRank.indexOf(closest) + 1; // cuz starts from 0 and we don't have rank 0
  console.log("min range: " + closest +
    " | our score: " + score +
    " | max range: " + pointsRank[rank])

  return {
    rank: rank,
    pointsLeftForNextRank: (pointsRank[rank] - score)
  }

}

const test1 = rank(pointsRank, 1200);
const test2 = rank(pointsRank, 2000);
const test3 = rank(pointsRank, 3700);

console.log(test1);
console.log(test2);
console.log(test3);


CodeChef's Tree MEX (Minimum Excludant) challenge

for p in permutations(all_vertices, v):

  \$1≤n≤10^5\$

Well, \$(10^5)! \approx \left(\frac{10^5}{e}\right)^{10^5} \approx 10^{35657}\$ so it's a waste of time trying to optimise this. The only thing to do is go back to the drawing board and spend a few hours thinking about the mathematics. At best the code you've written will serve to analyse all trees up to a small number of vertices (maybe 7 or 8) to see what patterns you can spot which can help to guide you in the right direction.


Java implementing task on another thread with javascript-like promise resolve-reject

the ServiceProvider is supposed to provide a singleton instance of UserService but it does not follow all the principles of the Singleton design pattern. specifically, the locking mechanisms that prevent multiple threads from creating multiple instances of UserService (or rather, multiple calling of the constructor)

and while on the subject - why not use Dependency Injection?

also, reject(response) is never called

with regard to the issue of the "javascript-like promise resolve-reject": Java has such a mechanism: CompletableFuture where you supply a Runnable and for the callbacks there are thenApply() thenAccept() and thenRun() methods.  exceptions are handled by exceptionally() method. There are other capabilities like chaining CompletableFuture instances (thenCompose().


Generating a warning when I/O size limit is exceeded

Apply Approved Verbs for Windows PowerShell Commands article from Windows PowerShell Cmdlet Concepts, use New-SoftAlert:

  Common Verbs

  Windows PowerShell uses the VerbsCommon enumeration class to
  define generic actions that can apply to almost any cmdlet…

  Verb (alias): New (n)

  Action: Creates a resource. (The Set verb can also be used when creating a resource that includes data, such as the Set-Variable
  cmdlet.)

  Comments: For this action, do not use verbs such as Create, Generate, Build, Make, or Allocate.


First of all, awesome that you have written tests!

However, your checker is a bit verbose on the matching case. It is often considered good practice for automated tests to be as noise-free as possible. Consider the following outputs:

Success for input=...testcase...
... 300 lines of success ...
Success for input=...testcase...
Result=... does not equal expected=... for input=...
Success for input=...testcase...
... 300 lines of success ...
Success for input=...testcase...

Ok, you have written just a few testcases, but I think you see my point: you'll miss the errors. Better would be just

Result=... does not equal expected=... for input=...

Failures: 1, Success: 601

Better: use a testing framework like unittest, py.test or doctest. Here's how it looks like doctest:

def insertion_sort(numbs):
    """
    >>> insertion_sort([5, 2, 4, 6, 1, 3])
    [1, 2, 3, 4, 5, 6]
    >>> insertion_sort([190, 2, 4, 6, 1, 3])
    [1, 2, 3, 4, 6, 190]
    >>> insertion_sort([-190, 2, 4, 6, 1, 3])
    [-190, 1, 2, 3, 4, 6]
    >>> insertion_sort([0, 0, 4, 6, 1, 3])
    [0, 0, 1, 3, 4, 6]
    >>> insertion_sort([0, 0])
    [0, 0]
    >>> insertion_sort([1, 0])
    [0, 1]
    """
    for cur_index in range(1, len(numbs)):
        cur_val = numbs[cur_index]

        lookup_index = cur_index - 1

        while lookup_index >= 0 and numbs[lookup_index] >= cur_val:
            numbs[lookup_index + 1] = numbs[lookup_index]
            lookup_index -= 1
        numbs[lookup_index + 1] = cur_val

    return numbs

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Now, this is a bit verbose, so my preference would probably to use py.test or nosetests, but the advantage of doctest is that it's built-in, and for simple tests it is sufficient.

Now, for another point. Your sorting is both in-place, and returns the list again.

For instance:

>>> example = [6, 7, 1, 2]
>>> result = insertion_sort(example)
>>> result
[1, 2, 6, 7]
>>> example
[1, 2, 6, 7]

Suggestion: if you do in-place sort, make sure it is documented that the function modifies the input array. In general, I would prefer not returning the result, as to limit confusion.

I can't really see anything wrong with the implementation itself, but I'm not familiar enough with insertion sort.

Using range is fine for short lengths, but as this is a list-sort, you don't really know the values len(numbs) will take. Maybe use xrange instead? (Or better: upgrade to Python 3!).

One thing I would really really like to advice is switching to Python 3 for learning. Python 2 is only supported up-to 2020, and a lot of people would be happy if more people learn Python 3 instead.


Inline Sum() vs query Sum() vs Where on a List object

I would go with the third, with the second as secondary choice.

The first mixes addition logic and comparison logic: it's not immediately clear that the zero is meant to exclude those objects, as opposed to giving a default for object.Area.

The second is better, but it hides the point behind a lot of unnecessary syntax.  The fact that you're working on object.Area and not record.Area gets lost.

The third is even better.  It can be conveniently read left-to-right, and all the information is grouped near what we're doing (condition is after the where, sum elements are after the sum).

Personally, I would use

double GetObjectArea(CustomObject obj, CustomEnum source)
{
   return obj.ListOfApplications.Count(p => p.Source == source) * object.Area;
}


Scanning a directory for plugins and loading them

I started a project with a structure similar to the one you detailed:

My first order of business was to move the import plugins out of the discover_dictionaries() function and to the top of the file.

My second order of business was to create an iterator which would iterate over the discover_dictionaries() generator and print what it had found:

for next_plugin in discover_dictionaries():
    print next_plugin

My third order of business was to create empty classes in each of the dict* paths, which looked similar to:

import os

class Dictionary:
    def __init__(self):
        pass

Following that, I added a print to the generator to see what it saw:

def discover_dictionaries():
    for plugin_name in os.listdir(PLUGINS_PATH):
        plugin_path = os.path.join(PLUGINS_PATH, plugin_name, plugin_name + '.py')
        print plugin_path

This gave me the following output:

C:/Users/jsanc623/PycharmProjects/AutoloadModules\plugins\dict1\dict1.py
C:/Users/jsanc623/PycharmProjects/AutoloadModules\plugins\dict2\dict2.py
C:/Users/jsanc623/PycharmProjects/AutoloadModules\plugins\dict3\dict3.py
C:/Users/jsanc623/PycharmProjects/AutoloadModules\plugins\__init__.py\__init__.py.py
C:/Users/jsanc623/PycharmProjects/AutoloadModules\plugins\__init__.pyc\__init__.pyc.py

If I put the same print statement inside the if os.path.isfile(plugin_path): block, the output was:

('dict1', <dict1.Dictionary instance at 0x0000000001FABA48>)
('dict2', <dict2.Dictionary instance at 0x0000000001FB04C8>)
('dict3', <dict3.Dictionary instance at 0x0000000001FB0F08>)

So, it does work. Now, let's see how we can clean it up.

The first thing I did was to get rid of BASE_DIR:

BASE_DIR = os.path.dirname(__file__)
PLUGINS_PATH = os.path.join(BASE_DIR, 'plugins')

as follows:

PLUGINS_PATH = os.path.join(os.path.dirname(__file__), 'plugins')

Next, we can get rid of class_ by replacing the yield statement from:

class_ = getattr(m2, 'Dictionary')
yield plugin_name, class_()

To a much simpler:

yield plugin_name, getattr(m2, 'Dictionary')()

Next, I added an if statement to return if it encountered a 'pyc' or 'init' file:

for plugin_name in os.listdir(PLUGINS_PATH):
    if 'pyc' in plugin_name or 'init' in plugin_name:
        return
    else:

We can also get rid of m1, by casting pathname:

fp, pathname, description = find_module(plugin_name, plugins.__path__)
fp, pathname, description = find_module(plugin_name, [pathname])
m2 = load_module(plugin_name, fp, pathname, description)

But, we can get even sneakier and get rid of the assignment on the first find_module by doing so:

fp, pt, dc = find_module(plugin_name, [find_module(plugin_name, plugins.__path__)[1]])
m2 = load_module(plugin_name, fp, pt, dc)

Which, granted makes our lines a little long. However, let's get a little crazier with our yield:

yield plugin_name, getattr(load_module(plugin_name, fp, pt, dc), 'Dictionary')()

So, in the end, the original would now look like:

import os
from imp import find_module, load_module
import plugins

PLUGINS_PATH = os.path.join(os.path.dirname(__file__), 'plugins')

def discover_dictionaries():
    for plugin_name in os.listdir(PLUGINS_PATH):
        if 'pyc' in plugin_name or 'init' in plugin_name:
            return
        else:
            plugin_path = os.path.join(PLUGINS_PATH, plugin_name, plugin_name + '.py')
            if os.path.isfile(plugin_path):
                try:
                    f, p, d = find_module(plugin_name, [find_module(plugin_name, plugins.__path__)[1]])
                    yield plugin_name, getattr(load_module(plugin_name, f, p, d), 'Dictionary')()
                except ImportError:
                    print('Error: could not import Dictionary from {0}'.format(plugin_path))

And it would still function. If you want to make it a bit more concise at the cost of iterating over 'pyc' and 'init' files, you can omit the if/else statement:

import os
from imp import find_module, load_module
import plugins

PLUGINS_PATH = os.path.join(os.path.dirname(__file__), 'plugins')

def discover_dictionaries():
    for plugin_name in os.listdir(PLUGINS_PATH):
        plugin_path = os.path.join(PLUGINS_PATH, plugin_name, plugin_name + '.py')
        if os.path.isfile(plugin_path):
            try:
                f, p, d = find_module(plugin_name, [find_module(plugin_name, plugins.__path__)[1]])
                yield plugin_name, getattr(load_module(plugin_name, f, p, d), 'Dictionary')()
            except ImportError:
                print('Error: could not import Dictionary from {0}'.format(plugin_path))

Readability out of the window, but we save assignments?


Using the interface is definitely an improvement, but what I lack in your code is common base exception, something like ServerException that could be used to distinguish other exceptions (e.g. IndexOutOfRangeException or whatever) from your exceptions (useful for catching).

That common base could be made abstract to force you to define HttpStatusCode

public abstract class ServerException: Exception {
//  standard constructors...
    public abstract HttpStatusCode GetHttpStatusCode();
}

Now, if you derive any custom exception from this (as you should, maybe creating some other abstract derived exceptions for some groups of problems), then you have to override (define) the code (or it would have to remain abstract and you won't be able to throw it).

public class UserAlreadyExistsExeption: ServerException {
//  again standard .ctors
    override public HttpStatusCode GetHttpStatusCode() => HttpStatusCode.Conflict;
}

Alternative would be to use public get-only property and initialize it in the constructor, maybe even having one exception type (and use try-catch-when), but I am not sure that can be used in your code (would require perfect 1-to-1 match between exception types and status codes).

Make message default

public class UserAlreadyExistsExeption: Exception, IHasHttpErrorCode
{
    public UserAlreadyExistsExeption(): base("User already exists") {}
}

and

throw new UserAlreadyExistsExeption();

instead of

throw new UserAlreadyExistsExeption("User already exists");

Maybe even handling localization in the default constructor, if needed.


Don't leave garbage laying around please, pick up after yourself.

'  End If

This doesn't have a purpose here, just get rid of it.

This isn't a good idea either

        Catch ex As Exception
            Return Nothing
        End Try

This was probably meant to close the connection, but there is a much better way to do that than to catch all exceptions and not report them.  Using Statements.

This is kind of smelly to me as well.

            Dim sSQL As String
            sSQL = "spGetProperty"
            dsNames.SelectCommand = sSQL

This simple Function doesn't need to be any more difficult than it has to be, you should do one of two things here.

Pass in the Stored Procedure Name as a string to the function
just set the SelectCommand to the name of the stored procedure like:

dsNames.SelectCommand = "spGetProperty"

It doesn't look like there is any reason whatsoever to call dsNames.SelectParameters.Clear() this object was created here and there is nothing in it yet, there should be no reason that you need to clear nothing.

Some other things that you don't need include

            Dim vIP As String = HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")

And

        'Public Function GetProperty(ByVal sUPRN As String, ByVal sUCARN As String) As apProperty

With all that I left in the Try/Catch statement because I didn't know exactly what you were needing it for, but this is what it would look like with all these changes.

Public Function GetProperty(ByVal sUPRN As String) As apProperty
    Try
        Dim oDetails As New apProperty
        Dim sConnString As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("SQL_DEMO").ConnectionString

        Using dsNames As New SqlDataSource
            dsNames.ConnectionString = sConnString
            dsNames.SelectCommand = "spGetProperty"
            dsNames.SelectCommandType = SqlDataSourceCommandType.StoredProcedure
            dsNames.SelectParameters.Clear()
            dsNames.SelectParameters.Add("ID", ID)

            For Each datarow As Data.DataRowView In dsNames.Select(DataSourceSelectArguments.Empty)
                With oDetails
                    .ID = datarow("ID").ToString
                    .BuildingNo = IIf(datarow("BuildingNo").Equals(DBNull.Value), "", datarow("BuildingNo").ToString)
                End With
            Next
        End Using
        Return oDetails
    Catch ex As Exception
        Return Nothing
    End Try
End Function


Function to check whether two strings are similar at given %

Alright I have a hole in my schedule, so I will give it a review myself.

Let's start with the function case_insensitive_chrcmp

The name mixes two standards for function name, the well-descriptive, but long snake_case and the less descriptive but shorter standard abbreviation naming.
So it would be better if it is either:

case_insensitive_char_compare
chrcasecmp

Since the second function uses the second standard, I would choose chrcasecmp.

Many people do not like one-liners as they actually require more space (or even ironically more lines) than if they were not a function at all.
Also it is a little bit slower (needs to access the routine, push the arguments onto the stack, etc). A good C function should be at least two lines and not more than a person with the old 640x480 monitor can see.
It can be optimized and shortened further using the bitwise XOR operator:

return ch1 == ch2 || (ch1 ^ ' ') == ch2;

Since ' ' translates to 32, which is the sixth bit set and others unset.

And the strpcmp function

I already said that two strlens to find the length of two presumably identical strings is not very efficient as it needs to iterate over both the strings, increment and check against '\0 at every iteration while this could be done in a single loop. This is an optimized function to find lengths of two strings:

int str2len (char* str1, char* str2, size_t * szStr1, size_t * szStr2)
{
    /* Variables */
    char*   p1      = str1;
    char*   p2      = str2;
    size_t  len1    = 0;
    size_t  len2    = 0;

    /* Pre-checking */
    if(str1 == NULL || str2 == NULL || szStr1 == NULL || szStr2 == NULL)
        return(-1);

    /* Processing */
    while(str1[len1] || p2[len2])
    {
        if(str1[len1] != '\0')
            len1++;
        if(str2[len2] != '\0')
            len2++;
    }

    /* Assignment */
    *szStr1 = len1;
    *szStr2 = len2;

    return 0;
}

int cur = 0; is declaration after expression, which turns the code into C89-incompatible. Also the name cur is not very descriptive. While it may mean "current" it is not clear current of what it is. Better name nMatch.
chars = szMax * setting / 100;
Does not define what happens if the result from the division is not a whole number. In most cases the floating point number will be omitted which may or may not be the desired behavior. I should consider using round(), floor() or ceil() on a double
The function checks if a char from str1 with index x matches a char with index x in str2 which makes the code susceptible to this scenario:
"Hello World" and "World" will always return false.
The function should rather search whether a characters are CONTAINED consecutively into the second string instead.


Simple exchange calculator in Java - structure and tests

First off, the implementation of lemonadeChange is pretty complicated. I get worried whenever I see a bunch of nested if statements - these always lead to bugs. Indeed, try adding another test case where you only pass $10 bills, I think it will erroneously return true. It's generally a good idea to limit the complexity of any individual function, take a look at the concept of Cyclomatic Complexity: https://help.semmle.com/wiki/plugins/servlet/mobile?contentId=29393453#content/view/29393453

Also, if you call lemonadeChange more than once on the same instance of CalculatorLongImp then the values of five/ten/acc will persist between calls, giving you odd results. Generally, you'd say this function has "side effects", and it's often a good idea to avoid these where possible.

It's good that you've included tests. I would separate these out so each test only covers a single implementation - specific tests covering a single function on a single class make it easier to see exactly what's broken.

Finally, I find the naming a bit confusing. What does acc do? What's the difference between CalculatorLongImp and CalculatorShortImp? Imagine someone else will be reading your code tomorrow and trying to understand what it does. Naming things clearly will make it much easier for someone else (or yourself in the future!) to read and understand your code.


You could try to replace some loops with string formatting, for example change this

for i in pol.vertices[:3]:
    out.write(str(i)+' ')
for i in pol.vertices[2:]:
    out.write(str(i)+' ')
out.write(str(pol.vertices[0])+' ')

to this

out.write('{0} {1} {2} {2} {3} {0} '.format(*pol.vertices))


PHP already has a native function for this task.

array_walk_recursive() traverses your "leaf nodes" for you in one step:

Code: (Demo)

//$multi=[1,2,[3,[4]],5];
$multi=[array('A',
        array('B',
            array('CC','CCCC','CCCCCC'),
            array('DDD','EFG','HIJ','LMNOP')
        )
    ),
    array('2'),
    'b',
    array(array(),array(),array())];
array_walk_recursive($multi,function($v)use(&$flat){$flat[]=$v;});
var_export($flat);

Output:

array (
  0 => 'A',
  1 => 'B',
  2 => 'CC',
  3 => 'CCCC',
  4 => 'CCCCCC',
  5 => 'DDD',
  6 => 'EFG',
  7 => 'HIJ',
  8 => 'LMNOP',
  9 => '2',
  10 => 'b',
)


Design
I applaud the goal of using struct and impl, but this is a good example of where object-oriented style can go wrong: it is not clear exactly what functionality Car and MPG encapsulate. Rather, these are just structs that carry some relevant data for the in_range function, but they do not seem to lead to a meaningful "separation of concerns" or make the code easier to understand as written.
For example, what is an MPG object? It carries a pair of a miles-per-hour and a miles-per-gallon, but why are these particular pieces of data grouped together and not with the other pieces of data? For Car, the primary problem is that it carries a lot of data but not enough functionality. If I were to reuse or extend your code, I would not be sure what to use a Car for, and whether and how I should extend Car with additional methods.
To improve your code, I would start by getting rid of MPG. Then, I would settle on a simple abstraction of a car that seems generalizable. We could start with this: a car is something that drives, given a certain amount of fuel, a fuel leak rate, a certain speed, and a certain fuel efficiency. Note that we no longer have efficiancy: Vec<MPG> as part of the car --- that muddles the meaning of a car, since it can then only drive at certain rates.
We might get something like the following design:
struct Car {
    fuel_remaining: f32, // Gallons
    fuel_leak_rate: f32, // Gallons/hour
    speed: f32, // Miles/hour
    efficiency: f32, // Miles/gallon
}
impl Car {
    fn new(
        fuel_remaining: f32,
        fuel_leak_rate: f32,
        speed: f32,
        efficiency: f32,
    ) -> Self {
        assert!(fuel_remaining >= 0);
        assert!(fuel_leak_rate >= 0);
        assert!(speed > 0);
        assert!(efficiency > 0);
        Self { fuel_remaining, fuel_leak_rate, speed, efficiency }
    }
    fn can_drive(&self, distance: f32) -> bool {
        let time = distance / self.speed;
        let fuel_req = time * self.fuel_leak_rate + distance / self.efficiency;
        fuel_req < self.fuel_remaining
    }
}

What I want to stress here is that the design is extensible:

First, we've articulated the requirements on our struct in the new function: which arguments must be greater than or equal to zero, possibly equal to zero, and so on.

Second, we've simplified the functionality to can_drive which just checks whether we can drive a given distance, but we could now imagine adding other functions, like fn drive(&mut self, distance: f32) to actually do the drive, fn out_of_gas(&self) -> bool to check if we are out of gas, fn fill_up(&mut self, new_gas: f32), and so on. These additional features would conceptually align with what the object is designed for.

A Note On Units
Although overkill for this example, another improvement to your design would be to make use of Rust's type system to keep different units separate at compile time. Here's how you would do that: first we define struct wrappers for each different kind of unit we are interested in:
struct Miles(f32):
struct Gallons(f32):
struct Hours(f32);
struct MPH(f32);
struct MPG(f32);

Then we can define operations like multiplication for the particular types which "make sense" to multiply. E.g.:
use std::ops::{Add, Mul};

impl Add for Hours {
    type Output = Self;
    fn add(self, other: Self) -> Self {
        self.0 + other.0
    }
}
impl Mul<Hours> for MPH {
    type Output = Miles;
    fn mul(self, time: Hours) -> Miles {
        self.0 * time.0
    }
}

and so on.
The beauty of this approach is that we get a compiler error if we make any arithmetic mistakes, like adding Miles to Hours. And moreover, that comes for free: in the actual running code, Miles and Hours both compile to plain f32 values.
Minutae
In addition to what the other answer said, run cargo clippy! It usually gives very helpful suggestions. Here you can replace remaining: remaining with remaining.  It would also be great to see some unit tests.


Recursively generating the look-and-say sequence

It seems like you tried too hard to avoid all loops by limiting yourself to .reduce() and recursion.  While JavaScript supports functional programming to some extent, sticking to pure FP everywhere will likely lead to clunky code.  A better strategy would be to define some functions that look pure from the outside, but might be implemented in an imperative style.  (Your code isn't pure FP anyway: the index += 1 statements perform mutation.)

I don't think that countStay and drill are well designed functions.  It's not clear to me what each of them is supposed to accomplish.  countStay seems to be a trivial wrapper around drill.  At first glance, all I can see is that drill contains a lot of code, and that it calls itself recursively.  In particular, it's hard to read because the variable names are cryptic.  map is obviously a map, and arr is obviously an array, but what are their purpose?

Suggested solution

I would define three functions, each of which has a clear purpose and is easily testable.  Instead of recursion, I've used iterateN, which is inspired by Haskell.  Then, it's easy to compose them to obtain the result.  This solution is simpler and more readable than yours.

/**
 * Split an array of items into runs of identical values;
 * yield [item, runLength] for each run.
 *
 * runLengthEncode('bookkeeper'.split('')) =>
 * ['b', 1], ['o', 2], ['k', 2], ['e', 2], ['p', 1], ['e', 1], ['r', 1]
 */
const runLengthEncode = function*(items) {
    if (items.length) {
        let groupStart = 0, groupItem = items[0];
        for (let i = 1; i < items.length; i++) {
            if (items[i] != groupItem) {
                yield [groupItem, i - groupStart];
                groupStart = i;
                groupItem = items[i];
            }
        }
        yield [groupItem, items.length - groupStart];
    }
};

/**
 * Given a number (as an integer or string), produce its successor
 * in the look-and-say sequence (as a string).
 *
 * nextLookAndSay('1211') => '111221'
 */
const nextLookAndSay = (n) => {
    let accum = [];
    for (let group of runLengthEncode(n.toString().split(''))) {
        accum.push(group[1], group[0]);
    }
    return accum.join('');
};

/**
 * The result of f(f(f ... f(init))), where the function f is applied n times
 * to the initial value.
 *
 * iterateN(2, (s) => s + 'o', 'b') => 'boo'
 */
const iterateN = (n, f, init) => {
    while (n--) { init = f(init); }
    return init;
};

console.log(iterateN(3, nextLookAndSay, '1'));


You should use the List#toArray method, you want to use the generic method, so not the one returning Object[], for this to work you need to supply an array of the correct size, such that it can store the data there.

List<String> list = ...;
String[] = list.toArray(new String[list.size()]);

Note that the array need not be the same size, there are two cases to consider:

If array.length < list.size(), then it will create a new array and return that one.
Else, it will put the data in the input array.


Your code looks nice and seems to be fully PEP 8 compliant indeed. The fact that you have 1 blank line between functions except in one place where you have 2 puzzles me a bit but that's not a huge issue.

You can actually make your code much easier. Here are a individual steps, you'll find the final code at the end.

Notice that you call turtle.forward(step) in each go_somewhere function. You might as well remove this and put it once and for all after your call to move_in_a_direction(step_size). Now, the go_somewhere function doesn't need to be given a step anymore.
Notice that the different function go_somewhere are just a call to setheading with a custom parameter. You could transform move_dict to map numbers to angles and call turtle.setheading(move_dict[random.randint(1, 4)).
Notice that your map is just converting 1 into 0, 2 into 90, 3 into 180, 4 into 270. This can be substitued with a simple operation : remove 1 then multiply by 90. You now have turtle.setheading((random.randint(1, 4) - 1) * 90).
Notice that generating an integer in [0, 1, 2, 3] makes things even easier as you don't need to remove 1.

Here's the corresponding code :

def make_random_walk(step_size, step_number):
    for _ in range(step_number):
        turtle.setheading(90 * random.randint(0, 3))
        turtle.forward(step_size)


In general the template looks like a good start. I noticed that the code appears to resemble the format advised in PHP-Fig's PSR-2, namely "The opening brace MUST go on its own line"1 for functions and methods plus control structures like if and else blocks. Most of the Javascript style guides I have seen call for curly braces to exist on the same line of the block they are opening. Personally I don't even agree with this in PHP, let alone Javascript, however if that is your personal preference then keep it consistent.

Inside the init method, there is an iterator:

return this.each(function(index)
{
    if(!$(this).hasClass("plugin_class"))
    {
        $(this).addClass("plugin_class");

       var $this = $(this);

The reference var $this = $(this); could be stored before the check of the class name and/or class name addition in order to reduce DOM queries.

Also, the name $this could be more descriptive - at least something like $element or $elem (as shown in the example under Provide Public Access to Secondary Functions as Applicable from the Advanced Plugin Concepts).

Addressing Your Additional question

You asked in a comment:

  what about the $.fn[plugin] part? I'm not sure about the first if statement. could that function be refactored and improved?

It is possible that ecmascript-6 features like the spread syntax could potentially be used to simplify the call, though given that current jQuery browser support includes IE 9+ it may not be wise to utilize ES-6 features.


Finding and returning a loopy path in a directed graph

You should use an array to check if you have already visited a node and not visits.contains(node), it would give you the answer in constant time instead of linear time.

The overall complexity of your algorithm is exponential. For instance, if you run your algorithm on this graph:

0 -> 1, 2, ..., n
1 -> 2, ..., n
...

where there are n nodes and there are edges from i to j iff i<j then the node i will be explored 2^i times.

Again you can solve this problem using an array (one array for all nodes) to ensure that each node is explored at most one time.


String trim functions with destination size limitation

Repeated code

size_t src_size = strlen(src) + 1;
if (src_size > dest_size) {
  return NULL;
}
return memmove(dest, src, src_size);

is a good candidate for a function (safe_memmove or something similar).

- Optimistic loops while (isspace((unsigned char) *src)) may never stop: '\0' is not a white space. Test for end of string explicitly:

    while (*src && isspace((unsigned char) *src))

  Red face above. I don't know what I was thinking.

Portability. A free-standing environment doesn't have to provide memmove or strlen or isspace. Only features confined in <float.h>, <iso646.h>, <limits.h>, <stdarg.h>, <stdbool.h>, <stddef.h>, and <stdint.h> are mandatory. I am afraid that to claim embedded portability you need to implement optional features yourself.

Sorry for nitpicking.


I would write an iterator for arrays that way:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArrayIterator<E> implements Iterator<E> {

    private final E[] arr;
    private int currentIndex = 0;

    public ArrayIterator(E... arr) {
        if(arr == null) {
            throw new IllegalArgumentException("Array is null");
        }
        this.arr = arr;
    }

    public boolean hasNext() {
        return currentIndex < arr.length;
    }

    public E next() {
        if (! hasNext()) {
            throw new NoSuchElementException();
        }
        return arr[currentIndex++];
    }

    public void remove() {
        throw new UnsupportedOperationException("Not supported.");
    }

}

To your second question: I assume you want to traverse the tree in-order, and that the nodes have no link to the parent, only to the children. Then you need a node list from the root node to the current node, which can store if a node was already visited or not, too.

Then you go left as deep as possible, storing the path in the node list. This is your first current node. When you need the next one, take its parent (from the node list).  Next would be the right children of that node (if there are any) or its own parent. The best way to understand this is to take a sheet of paper, draw different trees, and look how the traversal must work.


Moving files from a directory to multiple with names same as file

Like you noticed, no need to use multiple loops when you can do everything in one function and loop only once.

Aside from that, there are many small things that can be improved with this script:

This script doesn't work if the script is not in the same directory as the source directory. Correct if me I am wrong, but this is what I encountered when I tested the code. To allow for this flexibility (of using this script at any arbritary location), it is necessary to use absolute paths.
We should probably check if the directory we're about to create already exists. It may be possible that two images may have the same basename but different extensions. For this case, using os.path.exists will save us down the road and is simple to implement.
I noticed you excluded .DS_Store from filenames. I took it a step further and excluded all hidden files and files that started with __ (like Python build directories/files).
When using a loop comprehension for the sake of the for loop and not for the results, there's no need to store the output. For example, when using a = [making(directory) for directory in dirpaths], it is more useful to only write [making(directory) for directory in dirpaths] on that line. Storing it as a result implies that the output is being used somewhere later in the script, when in this case, it is not useful in the final version.
It is better to use shutil.move for the movingfiles function. Under the hood, Python will decide whether to use os.rename or if a copy-remove operation is neccesary (see shutil.move for more information).
Using os.makedirs is overkill for this example here. os.makedirs is meant for recursively creating directories, not for single-level directory creation. The similiarily named os.mkdir is more appropriate here and probably will be more performant.
It is not necessary to check if the source directory string contains a '/'. On the documentation, os.path.join verifies that the result will have "exactly one directory seperator". Therefore, we don't have worry about extra logic.
Normally, I wouldn't bother with optimization when the context of the script is for running a few files. In the case of the thousands of objects, however, it is crucial to reduce how many loops we run. In the code below, you see implicit use of generators. Specifically, we will lazily evaluate our list of filenames upto the point we process each filename. This means we only run through our list of filenames once(!)
On the topic of performance, when we have a custom function defined (read: not lambda), it almost always better to use map when we don't require storing the output. On Python2, the advantage was neglible, but on Python3, the difference is noticable. So we will use map below. (map is very much faster when using builtin Python functions that call on C code. Why? Because map also reaches down to C, meaning you get a barebones C loop for those operations. Looping in Python is unintuitively bloated compared to C.)
The use os.path.splitext is correct for this script. However, there is a slight performance cost to using this function, and so I opted for the leaner .split('.', 1)[0] which is faster. As long as the filenames don't contain '.' other than at the end as an extension, we'll be fine.

#!/usr/bin/env python
import os
import shutil
import argparse
import functools

def mkdir_move_file(file, source):
    directory = file.split('.', 1)[0]
    if not os.path.exists(directory):
        os.mkdir(directory)
    shutil.move(file, directory)

def mkdir_move_all_files(source):
    if not os.path.exists(args.source):
        raise Exception('Source folder cannot be found or does not exist!')
    filenames = (os.path.join(source, x) for x in next(os.walk(source))[2]
                 if not x.startswith('.') and not x.startswith('__'))

    # basically the same as [mkdir_move_file(file, source) for file in filenames]
    map(functools.partial(mkdir_move_file, source=source), filenames)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Make folders for loose files in folder.')
    parser.add_argument('source', action='store', type=str, help='The source directory to process.')

    args = parser.parse_args()

    mkdir_move_all_files(args.source)

Some further notes, beyond the initial scope of the question:

Python makes it simple to create scripts-- the key is using the argparse library. This library lets us parse arguments given through the command line, which can then be passed along the functions internally. Simply add parsing to your script and you can use the executable script from the command line!
If our mkdir_move_all_files function was more complicated/intensive, we could use asynchronous programming to speed up our overall program. That way we can fire off multiple evaluations without waiting for the result to complete. However, I don't see it being hugely beneficial for this case.

If you have any questions let me know.


Printing an arrow of asterisks in Haskell

The way you're actually generating the list of Strings seems fine, but the formatting, at least in my opinion, can be improved: since raisingAsterisks and decreasingAsterisks are both relatively small "helper" functions for arrow, I would suggest putting them inside a where clause to make things a little easier to read.

arrow :: Int -> [String]
arrow n = increasing ++ tail decreasing
    where increasing = take n $ iterate ('*' :) "*"
          decreasing = reverse increasing

In this context, the variable names could be shortened, due to the fact that it's easy to understand what's happening. Note that the n variable no longer needs to be passed, so increasing and decreasing actually are no longer even functions!

I hope you agree that changing your code just a little greatly improves readability.


Visualization of bubble sort in progress

Your code works nicely.

In BubbleSort I would move the definition of iTemp to the point of first use.  The name iTemp is ugly and the 'i' makes me think you are using a type prefix (as does the 'p' in pData). I don't know anyone who thinks that is a good idea - just use temp and data.

In RepaintScreen I don't see the need to buffer the data yourself.  You can just use stdio to buffer it for you:

static void RepaintScreen(const int *data, int count, int p1, int p2)
{
    for (int i = 0; i < count; i++) {
        fputs((i == p1 || i == p2) ? "-->" : "   ", stdout);

        for (int j = 0; j < data[i]; j++) {
            putc('|', stdout);
        }
        putc('\n', stdout);
    }
}

If you do accumulate a string, using strcat is inefficient and prone to buffer overflow. It is inefficient because on each call it must traverse the whole string to find the end. It would be better to keep track of the end of the string yourself.  For example:

static void RepaintScreen(const int *data, int count, int p1, int p2)
{
    system("cls");
    char buf[(WIDE + 1) * (SIZE)];
    char *b = buf;

    for (int i = 0; i < count; i++) {
        if (i == p1 || i == p2) {
            *b++ = '>';
        } else {
            *b++ = ' ';
        }
        for (int j = 0; j < data[i]; j++) {
            *b++ = '|';
        }
        *b++ = '\n';
    }
    *b++ = '\0';
    fputs(buf, stdout);
}

Overflow occurs if you get the size of the buffer size wrong. Avoiding overflow is messy as you must check that there is enough space each time you insert into the buffer and exit sensibly if there is not. Using fputs/putc, as shown above, avoids overruns.


Inserting a record into a MySQL table using PDO

No, it's not vulnerable to SQL Injection, as you use prepared statements, and you use them correctly.

If you don't have any CSRF protection it is however vulnerable to XSS because of the echo (and of course CSRF), but I'm assuming that that's more of a debug statements.

Misc

You don't really need the variables nameone and nametwo. One-time variables are only useful if you need to give them some name to increase readability.
You shouldn't use mysql_*. So if you want to set the character set you should use PDO (you can also pass it as optional MYSQL_ATTR_INIT_COMMAND parameter when initializing the connection, see eg here).
try to be consistent with your names (nome vs name).
use camelCase to make your names easier to read (nameone -> nameOne).


Find largest two numbers from list using clojure

This looks like a clean way to find the max two elements. It can be shortened a little bit with destructuring:

; Accumulator function for reduce later
(defn top-two [[big1 big2 :as acc] x]
  (cond
    (> x big1) [x big1]
    (> x big2) [big1 x]
    :else acc))

(defn top-two-list [coll]
  (reduce top-two [0 0] coll))

You could also write something like so:

(defn top-two [coll]
  (let [big1 (apply max coll)
        big2 (apply max (remove #(= big1 %) coll))]
    [big1 big2]))

But I think it is programmer preference which you prefer. Both solutions are O(n), however the second ends up scanning the list twice.


F# function to concatenate some DSL scripts with indentation

I'll start with the code and explain after

let foldScript =
  let isScriptNonEmpty { Script = script } = script <> ""
  let foldAppScripts =
    let foldScripts = Seq.fold (fun acc { Script = script } -> sprintf "%s\r\n%s" acc script) ""
    Seq.groupBy (fun { App = app } -> app)
    >> Seq.map (fun (app, group) -> sprintf "\r\n\tuse Application = %s  %s" app <| foldScripts group)
    >> Seq.fold (sprintf "%s%s") ""

  Seq.filter isScriptNonEmpty
  >> Seq.groupBy (fun { Store = store } -> store)
  >> Seq.map (fun (store, group) -> sprintf "use Store=%s%s" store <| foldAppScripts group)
  >> String.concat "\r\n"

let s = [ { Store = "s1"; App = "a1"; Script = "script1" }; { Store = "s1"; App = "a2"; Script = "script2" }; { Store = "s2"; App = "a3"; Script = "script4" }]
let r = foldScript s

First I made inner "function" to ease readability and reused the Script type Reed talked about because it's a good idea
Then you can pattern match (deconstruct) on record almost anywhere so
(if there are multiple record type with same field name you'll have to qualify it but that's not the case here)
The foldAppScripts "function" have itself an inner "function"
I choose to favor function composition (and so made "function value") if it doesn't suit you, you can put back the argument and pipe over it
I used the backward pipe to avoid using parenthesis (also a matter of taste)
The last Seq.fold of foldAppScripts use eta-reduction (transforming fun arg -> fct arg in just fct)
Your script.ToString () isn't needed as script is already a string
I replace your last fold by a call to String.concat

Performance wise you could try to use a StringBuilder (and use Printf.bprintf) but it's not so easy to use

We could go further and remove each lambda by a named function (self documentation) but that's maybe overkill.

Edit

After toying a little more with this I think I managed to make the StringBuilder version working.
Not sure it was worth the effort my (simplistic) measurements show a quicker first version (some ms for 100k items so negligible) but the second has a little less pressure on GC gen 1
But that was mainly for the experiment (I finally used Printf.kbprintf)

here is the code :

let foldScript storeAppScripts =
  let builder = System.Text.StringBuilder (60 * Seq.length storeAppScripts)
  let bprintf format = Printf.bprintf builder format
  let kbprintf continuation format = Printf.kbprintf continuation builder format

  let isScriptNonEmpty { Script = script } = script <> ""
  let writeAppScripts storeAppScripts () =
    let writeScripts scripts () = Seq.iter (fun { Script = script } -> bprintf "\r\n%s" script) scripts

    storeAppScripts
    |> Seq.groupBy (fun { App = app } -> app)
    |> Seq.iter (fun (app, group) -> kbprintf (writeScripts group) "\r\n\tuse Application = %s  " app)
    bprintf "\r\n"

  storeAppScripts
  |> Seq.filter isScriptNonEmpty
  |> Seq.groupBy (fun { Store = store } -> store)
  |> Seq.iter (fun (store, group) -> kbprintf (writeAppScripts group) "use Store=%s" store)

string <| builder.Remove (builder.Length - 2, 2)

First I put back arguments because it's no more just function composition in the bodies.
I created a StringBuilder and gave him an initial capacity
The Seq.length means a first loop over the items so the diff in perf comes probably from there but without a proper capacity it'll suffer from many internal buffer resizing
Then I made some helper for bprintf and kbprintf embedding the builder
eta-reduction isn't possible for bprintf because it would then be a value and not a function so it wouldn't be generic
I renamed the inner function to reflect the change in code they now return unit
The extra unit parameter isn't strictly required it just allow me to do eta-reduction at call site as kbprintf continuation argument expect a unit -> 'a
The rest of the code is nearly the same ; some Seq.map changed in Seq.iter because of the unit return.
The Seq.fold vanished which probably means I could simplify the Seq.map (...) >> Seq.fold in just a fold in the first version
At the end I remove the trailing "\r\n" added by the last call to writeAppScripts ; I wanted to find a better way without luck.

Now a little explanation about how bprintf and kbprint works :

bprintf is "easy" it's a printf which write it's content into the Stringbuilder given (same principle as fprintf with a file)
kbprintf do the same but take a continuation (a function) which will be executed after (for example to transform the result into another object)
I could have not used it and just put multiple bprintf instead
So for example kbprintf (writeAppScripts group) "use Store=%s" store will first write "use Store=XXX" into the StringBuilder and then call writeAppScripts on the group value which will add it's content into the StringBuilder


Don't fetishise List<>

            List<I> xi = (from c in ids.Items
                          where !(
                                    from b in c.T.ToList()
                                    select b.n
                                  ).Contains("_parent")
                          select c
                 ).ToList<I>();

c.T is an array: what benefit is there to calling ToList() on it? There are two reasons for using ToList() on an enumerator: it's a lazy enumerator which you want to evaluate fully, or you need some specific method from List. Here neither of these applies.

It's not clear to me that xi needs to be eager either. I think that a first refactor could be to

            var xi = (from c in ids.Items
                          where !(
                                    from b in c.T
                                    select b.n
                                  ).Contains("_parent")
                          select c
                 );

Personally I'm not a fan of the SQL-like LINQ syntax. I'd find this more readable as

            var xi = ids.Items.Where(item => !item.T.Any(t => t.n == "_parent"));

There are various other instances of the same unnecessary or even counterproductive use of ToList().

Learn the LINQ overloads

                String nameId = iobj.T.ToList()
                    .Where(zxc => zxc.n.Equals("_display_name"))
                    .First().Value;

Instead of Where(...).First() you can just use First(...):

                String nameId = iobj.T.First(zxc => zxc.n.Equals("_display_name")).Value;

Don't do pointless work

            while (xi.Count > 0)
            {
                foreach (I iobj in xi)
                {
                    String nameId = ...;

                    String parentId = ...;

                    // Do a lot of work with nameId
                    ...

                    TreeNode ttmp = FindNode(treeView1.Nodes, parentId);
                    if (ttmp != null)
                    {
                        ttmp.Nodes.Add(treeNode);
                        xi.Remove(iobj);
                        break;
                    }
                }
            }

A given I instance might not find its parent until the 100th time round the outer loop, which means that 99 times it will construct a node and then hand it off to the garbage collector without it ever being needed. That's not only bad for performance: it's confusing for the maintenance programmer. Compare this rewrite:

            while (xi.Count > 0)
            {
                foreach (I iobj in xi)
                {
                    String parentId = ...;

                    TreeNode ttmp = FindNode(treeView1.Nodes, parentId);
                    if (ttmp != null)
                    {
                        String nameId = ...;

                        // Do a lot of work with nameId
                        ...

                        ttmp.Nodes.Add(treeNode);
                        xi.Remove(iobj);
                        break;
                    }
                }
            }

Avoid linear time insertions, deletions, and searches where possible

E.g.

                    String nameId = iobj.T.ToList()
                        .Where(zxc => zxc.n.Equals("_display_name"))
                        .First().Value;

                    String parentId = iobj.T.ToList()
                       .Where(zxc => zxc.n.Equals("_parent"))
                       .First().Value;

Even rewriting that to ditch to ToList() and use First(...), it's doing multiple linear searches through the same array. I would want to investigate whether I could refactor to replace IT[] T with IDictionary<string, string> T.

If I can't, I would strongly consider introducing a local struct or class to wrap iobj, nameId, and parentId so that the search can be done once.

Then in this main loop, xi has elements at random positions selected for removal. In that case it should under no means be a List<>. ISet is far more appropriate for random removals.

FindNode isn't supplied, but I suspect that it also does a linear search. There's nothing stopping you from introducing an IDictionary<string, TreeNode> to find the parents quickly.

Think in parallel

(Or: a lot of the preceding was because they're important lessons, but I'm now going to recommend throwing most of the code away and rewriting from scratch).

Why is it necessary to first find the roots and then build parents? And why is it necessary to break out of the inner loop in the second half when you've found a node whose parent is already in the tree? [NB That's a rhetorical question: I know that you're doing it to avoid a concurrent modification exception, but there are standard workarounds for that which are less inefficient].

In particular, is there any reason not to structure things like this?

IDictionary<string, Tuple<I, TreeNode>> nodes = ids.Items.ToDictionary(
    item => ...,
    item => ...);

foreach (var pair in nodes.Values)
{
    if (ItemHasParent(pair.Item1))
    {
        TreeNode parentNode = ...;
        parentNode.Nodes.Add(pair.Item2);
    }
    else
    {
        treeView1.Nodes.Add(pair.Item2);
    }
}


Does using SharedPreferences drain resources?

Accessing SharedPreferences takes some definite amount of time because they are written and read from an actual file. So if you call this code too often from your mainThread, you will end up with ApplicationNotResponding errors and a bad user experience. The point is to call this on a background Thread (java) or coroutine(kotlin). The same goes for accessing the network, reading and writing to the database, long calculations etc

https://developer.android.com/training/articles/perf-anr


Recursively Convert Roman Number to Integer

Writing down all your basecases takes a lot of space. I would instead use a dictionary, which could even be a global constant.
I find using n as an argument for something that is not an integer to be misleading. A generic x or s or roman_numeral would be clearer, IMO.
Python has an official style-guide, PEP8. It recommends using four spaces as indentation.
BASE_CASES = {"": 0, "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1}

def roman(s):
    """Takes a roman number x as an argument and returns an integer.
    Assumes that the string is correctly written, i.e. it provides no error-checking.
    """
    if s in BASE_CASES:
         return BASE_CASES[s]

    # If a smaller number precedes a bigger number,
    # then the smaller number is to be subtracted from
    # the bigger number. Else, it has to be added:
    first, second = map(roman, s[:2])
    if first < second:
        return second - first + roman(s[2:])
    else:
        return first + roman(s[1:])

Of course, using a recursive approach in Python is usually not the best idea, converting it to an iterative approach is much better (i.e. usually faster and not fraught with stack limit issues):
from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def roman(s):
    if s in BASE_CASES:
        return BASE_CASES[s]
    return sum(first if first >= second else second - first
               for first, second in pairwise(map(BASE_CASES.get, s)))


The idea of creating a Value Object instead of using primitives is to have a highly descriptive domain. Using the second option (the extension method) misses the point. You definitely want to be using the first.

e.g.

public class QuestionAnswer
{
    public int QuestionId { get; set; }

    public YesNoAnswer YesNoValue { get; set; }
}

Is more descriptive and specific than:

public class QuestionAnswer
{
    public int QuestionId { get; set; }

    public bool YesNoValue { get; set; }
}

or

public class QuestionAnswer
{
    public int QuestionId { get; set; }

    public string YesNoValue { get; set; }
}

One thing I would add is that you probably want a conversion to bool:

public class YesNoAnswer
{
    // omitted

    public static implicit operator bool(YesNoAnswer answer)
    {
        return (answer?.Yes).GetValueOrDefault();
    }

}

Then you can use it naturally in code:

var someAnswer = new QuestionAnswer { QuestionId = 1, YesNoValue = new YesNoAnswer("YES") }:

if (someAnswer.YesNoValue)
{

}

You should also override Equals and GetHashCode as Value Objects should have value equality not reference equality.


Convert sum from monthly to quarterly values

You could use panda's resample to group your data into quarterly blocks. I think the key thing to note is that your dates start at the end of the month, so you need to set it to resample from the start of the month. The main problem is that the rest of your columns don't really aggregate well, but you can just update them from the original data by index.

def convert_to_quarterly(df):
    """Aggregates 3 months of data to a quarterly value."""
    df.date = pd.to_datetime(df['date'])
    df = df.set_index("date")
    agg_columns = ['data_1', 'data_2']
    extra_cols = [x for x in df.columns if x not in agg_columns]
    df_out = df.resample("QS-JUN")[agg_columns].sum()
    df_out.index = df_out.index + MonthEnd(1)
    df_out[extra_cols] = df[extra_cols]
    return df_out

data = convert_to_quarterly(data)

Since we resampled by month start, if you want the dates to be from the end of the month, you can use pandas.tseries.offsets MonthEnd to fix your dates.

Alternatively, you could keep your rollingsum method and just generate your quarter end dates by a daterange:

pd.date_range(data.date.min(),data.date.max(),freq="Q")

Also, converting the date column and setting it as index is not really the responsibility of a monthly_to_quarterly function, so you might want to consider separating the concerns and doing that outside of the function from a design perspective.


You could cut your code in half if you used a map:

typedef   std::map<std::string, unsigned int> Map;

Map tMap;
while(std::cin >> word)
{
    // When accessing a map with `[]` If the value does not exist
    // it is created and initialized to zero.
    //
    // The plus plus then increments the stored value
    tMap[word]++;
}

// Iterate through map and print frequency

Couple other notes from the code you have:

After unique_words.push_back(words[0]); you can start the i loop at index 1 instead of 0.
When checking for uniqueness in the first pair of loops, once you determine uniqueness to be false you can stop looping for that word: while(j < unique_words.size() && isUnique) ...