Accessing the contents of a project's root directory in Python

I never heard of __root__.py and don't think that is a good idea.

Instead create a files.py in a utils module:

MAIN_DIRECTORY = dirname(dirname(__file__))
def get_full_path(*path):
    return join(MAIN_DIRECTORY, *path)

You can then import this function from your main.py:

from utils.files import get_full_path

path_to_map = get_full_path('res', 'map.png')

So my project directory tree looks like this:

project_main_folder/
    utils/
        __init__.py (empty)
        files.py
    main.py

When you import a module the Python interpreter searches if there's a built-in module with that name (that's why your module name should be different or you should use relative imports). If it hasn't found a module with that name it will (among others in sys.path) search in the directory containing your script. You can find further information in the documentation.


Separating and organising modules with objects?

I would recommend you use a closure like this:

var Obj = (function() {
    var privateState = null;
    return {
        A: 1,
        B: true,
        C: function() {
            return privateState;
        }
    };
})();

The biggest reason why this is a good idea is that it adds the ability to keep private state within the closure. Normally you can define private properties by convention but as the complexity of an object increases the better it is to keep certain things private.


In benchmarking various techniques for this question, I found the biggest speed boost was in abandoning string conversion in favor of %10 to get the individual digits - try using a method like this to get your sums:

def sum_square_digits(n)
  sum = 0
  until n == 0
    sum += (n % 10) ** 2
    n /= 10
  end
  sum
end


You could use findall with a pattern like (cell)|(wolf|wolves) and check if every group was matched:

words = (("cell",), ("wolf","wolves"))
pat = "|".join(("({0})".format("|".join(forms)) for forms in words))
regex = re.compile(pat)
for sentence in sentences:
    matches = regex.findall(sentence)
    if all(any(groupmatches) for groupmatches in zip(*matches)):
        print sentence


Program to implement Merge Sort Algorithm

Is this the most efficient way to do it?

No.  First thing, if efficiency is your goal, you don't use mergesort for small inputs.  An insertion sort is lower overhead for small inputs.  I don't know where the crossover point is, but it is almost certainly higher than one.  So

if(arr.length<2)
    return;

would become something like

if (arr.length < MINIMUM_MERGESORT_SIZE) {
    insertionSort(arr);
    return;
}

Allocating and copying arrays

int rightLength;
if((arr.length&1)==0) //if even
    rightLength = mid;
else
    rightLength = mid+1;
right = new int[rightLength];

This seems rather complicated.  Consider

int[] right = new int[arr.length - left.length];

Same result.  Less code.  I don't know that it changes the efficiency that much, as the operations are pretty cheap.  But it does ensure that you don't accidentally create an error by messing up the length calculation.

What has a better chance of improving efficiency is combining the allocation above with the copying.  So get rid of the declarations and

for(int i=0;i<mid;i++)
    left[i] = arr[i];

for(int j=0;j<rightLength;j++)
    right[j] = arr[j+mid];

Now we can just say

    int[] left = Arrays.copyOfRange(numbers, 0, numbers.length / 2);
    int[] right = Arrays.copyOfRange(numbers, left.length, numbers.length);

This will take advantage of other optimizations, like copying blocks of memory at once.  It likely also avoids clearing the new array, as we copy over those values anyway.

I changed the name of arr to numbers, which I find more descriptive.  Another complaint you'll hear about arr as a name is it makes everyone sound like a pirate when they say it.  But more professionally, abbreviating by a small number of characters doesn't help much.  You could have just said array.

I added more indentation.  Usually we indent every time we have a { and remove indent every time we }.

Alternatives

Of course, if we really wanted to sort efficiently, we'd just say

    Collections.sort(numbers);

We'd let it work out what method and how to split up the arrays.  But you may be trying this purely as an exercise.


Knapsack algorithm in JavaScript - Integer weights and values

I don't think your algorithm actually works.

First...

while (totalWeight < capacity) {

...is not the proper criteria for determining when loading into the knapsack should be completed.  What if the knapsack capacity is 10 and you got passed 4 objects each having weight of 3?   The most you could ever get in the knapsack is a weight of 9.  With your condition as is, you would get an infinite loop.

Second...

    totalValue += ratio;

...makes no sense.  Why are you adding the value/weight ratio to the total value summation?

Third...

    totalWeight++;

...also makes no sense. Why are you incrementing the total weight?

Probably something like the following is what you would need

function knapsack(items, capacity) {
    let totalValue = 0;
    let totalWeight = 0;
    let remainingItems = items.sort( (a, b) => {
        return (b.value / b.weight) - (a.value / a.weight);
    });
    while (remainingItems.length > 0) {
        const remainingCapacity = capacity - totalWeight;
        remainingItems = remainingItems.filter( (item) => {
            return (item.weight <= remainingCapacity);
        });
        if (remainingItems.length === 0) continue;
        const addedItem = remainingItems.shift();
        totalValue = totalValue + addedItem.value;
        totalWeight = totalWeight + addedItem.weight;
    }
    return totalValue.toFixed(2);
}

Note that this would work even with floats, however this does not validate input data against weight = 0 items which would cause error.  In production code, it might be needed to validate the item being passed against this (and possibly other things like negative values/weight, negative/zero capacity, etc.)


Checking to see if all values in an array are equal

[Rewritten]

You want to avoid inject, as uniq.size is O(n) and clearer. Monkey patching array makes the code clearer and is idiomatic Ruby. Methods that return a boolean should end in ?. Method names should be snake_case. Here you go:

class Array
  # Check to see if all values in the first dimension are equal
  def constant_1d?
    uniq.size == 1
  end

  # Check to see if all values in the second dimension are equal
  def constant_2dy?
    all?(&:constant_1d?)
  end

  # Check to see if all values in the third dimension are equal
  def constant_3dz?
    all?(&:constant_2dy?)
  end
end


First, I'd not name the function findLongestWord as you're not looking for the longest word, but the length of the longest word. Try getLongestWordLength instead.

You're forgetting var for your variables. This makes them shoot up to the global scope and be declared there, and we don't want that to happen. For ES6, there's also let.

for-in is only advisable on objects, and even on objects you guard it with hasOwnProperty. That's because it iterates through prototype properties (things other than the array elements or instance properties). A regular loop (for or while) while incrementing an index until length would be better. But there's an even better approach...

You can create a map of lengths by using map on your split string, returning the length of the strings. Then you use Math.max to get the largest number in the array of lengths. We can use the spread operator (...) to spread the array as arguments to Math.max.

function getLongestWordLength(str){
  return Math.max(...(str.split(' ').map(s => s.length)));
}

The above is ES6 syntax. The ES5 equivalent would look like the following. One notable difference, aside from the more verbose map is the use of apply to provide Math.max with a dynamic set of arguments.

function getLongestWordLength(str) {
    return Math.max.apply(Math, str.split(' ').map(function (s) {
        return s.length;
    }));
}

document.write(getLongestWordLength('The quick brown fox jumps over the lazy doge'));


General comments

You should read the manual pages on time(), which gives you the time in seconds since 1970, library functions such as localtime, strftime and ctime that can be used to present time values and the sleep() function, which sleeps the process for a specified
  number of seconds.

Also:

variables and structure fields are normally not all-uppercase (X,Y,MIN)
put a single definition or expression on each line
leave a blank line between functions.
printf has many formatting options.  Of relevance here is the "%02d"
format string which prints an integer in 2 places, zero-padded if necessary

So for 1, it prints '01' and for 10 it prints '10'.
I prefer to see a space after while and if etc. and spaces around
operators (!=, %, / etc)
make all functions static where possible (in this program, all except
main)

- your function delay is not a good way of delaying, as it ties up the processor.  Better use sleep

Function showClock

I presume you wanted to call delay, but you didn't.  This function loops
continually using 100% of CPU time.  Better would be to use sleep() which
lets other processes run. So sleep(1) would sleep for 1 second.
using time() would be better than clock(), as you want intervals in
seconds
the single printf format "%02d:%02d:%02d" does what you want without pasing
three x-coordinates to the function
most of the rest is unnecessary if you use sleep and time and the other library functions to present the time interval


Some other things that you can try, short of trying a totally different algorithm:

rename all_numbers to prime_candidates and remove composite numbers from it. (list_of_nonprimes.Add(i * j); -> prime_candidates.Remove(i*j). Avoiding the Except at the end.
You can also hold which numbers are non primes in an array of bools and lose all the HashSets. Changing:

list_of_nonprimes.Add(i * j)

to

nonprimes[i*j] = true;

Thus avoiding a bunch of hash lookups. After the loops sum up any n s.t. nonprime[n]==false
You can also use a BitArray instead of a bool array. Because it is more space efficient it might reduce cache misses.

Of course, you can only be sure if any of these actually makes any improvement after you try.


Handling vertices multiple times
There are two places where you are doing extra work because you are handling vertices multiple times:

When you find a shorter path to a vertex, you currently push that vertex with the new path length into your priority queue.  While this works, you still have the old vertex in the priority queue as well.  You will eventually pop the vertex off twice (and handle it twice), which is not ideal.  If you kept track of which vertices you've already handled, you could quickly skip duplicate vertices when you come across them.

When you handle a new vertex, you iterate over all of its edges.  But if you see an edge to a vertex that has already been handled, you don't need to deal with it.  Right now, you could be pushing vertices back onto your priority queue that you've already dealt with.


Loop Animation on several UIButton's NSLayoutConstraint

I'm not completely familiar with animating auto-layout constraints.  Fortunately (or unfortunately), I've not yet ever had the need to do this.  So, I'm not sure if there's a better way, but I'd say if it's working, that's a good sign.

What I do want to comment on is your readability:

constraint.constant = toShow?0:-theButton.frame.size.width;
[self.view setNeedsUpdateConstraints];

I don't mind ternary operators.  But I think you really need to include some white space.  When it's all smushed together, and including the negative sign, I had to do a double take before I realized what's going on.

constraint.constant = toShow ? 0 : -theButton.frame.size.width;

[UIView animateWithDuration:1 delay:i *(toShow?0.1:0.05) usingSpringWithDamping:10 initialSpringVelocity:toShow?20:-20

  options:UIViewAnimationOptionCurveEaseIn animations:^{
          [self.view layoutIfNeeded];
      } completion:nil];

This method call suffers the same problems as before with the smushed ternary operator, except it's worse because this method has so many more arguments and you're calculating so much in line and you're not using any vertical space.

I'd rewrite this as such:

CGFloat animationDelay = i * (toShow ? 0.1 : 0.05);
CGFloat springVelocity = toShow ? 20 : -20;

[UIView animateWithDuration:1
                      delay:animationDelay
     usingSpringWithDamping:10
      initialSpringVelocity:springVelocity
                    options:UIViewAnimationOptionCurveEaseIn
                 animations:^{

    [self.view layoutIfNeeded];

               } completion:nil];

With that spacing, even if we kept the ternaries in-line, it's still significantly more readable with a single argument per line.


What is the simplest way to hide labels and inputs with javascript?

I would use a combination of CSS and JavaScript for this use-case. Essentially what you want to achieve is a simple solution to showing and hiding form elements.

This is what I would suggest for markup:

<form id="myform" method="POST" action="/some/processing/script">
    <fieldset id="group-a" class="input-group">

            My Element Label
            <input type="text" id="my-input-element-1" value="" />

    </fieldset>
</form>

CSS:

#myform label {
    display: block;
    margin: 0 0 10px 0; /* Set the bottom margin to whatever you want */
}

#myform label > span {
    display: block;    /* display:block will force the input element below it */
    margin: 0 0 3px 0; /* Set the bottom margin to whatever you want */
}

#myform label > input[type="text"] {
    display: block;    /* The default is inline, but we want to span the whole width */
    width: 100%; /* Full width */
    padding: 5px 0; /* Trick to allow an input to span the full width, without poking out of the containing element */
    margin: 0; /* Set the bottom margin to whatever you want */
    text-indent: 5px; /* Indent the text to make it appear normally */
}

#myform label.hidden {
    display: none !important;
    visibility: hidden !important;
}

/* OR */

.hidden {
  display: none !important;
  visibility: hidden !important; /* Prevent element from affecting the box model, e.g. whitespace between visible, surrounding elements  */
}

Now, with this setup in mind, you should only have to add or remove the class .hidden from either the containing  element or apply it to the <fieldset /> element if you want to hide the whole group.

Also, if you're going to go to the trouble of hiding input fields, I'd recommend setting the disabled attribute, e.g. <input type="text" disabled="disabled" /> to prevent it's values from being serialized/submitted as part of the form.


Grouping sub-arrays with nonidentical items

Cascaded ternaries, generic variable names, obfuscated logic produces write-only and mind-boggling code that requires deciphering for anyone, including you in the future.

Let's try to write a self-explanatory code:

function groupUnique(input) {
    let results = [];
    for (let inputRow of input) {
        let collectedCells = new Set(inputRow);
        let draft = [inputRow].concat(
            input.filter(row => {
                if (row.some(cell => collectedCells.has(cell)))
                    return false;
                for (let cell of row)
                    collectedCells.add(cell);
                return true;
            })
        );
        let alreadyAdded = results.some(res =>
            res.length == draft.length && res.every(row => draft.includes(row))
        );
        if (!alreadyAdded)
            results.push(draft);
    }
    return results;
}


Rather than performing a rotation k times, perform one rotation of k places.

So, you have an array [5, 4, 3, 2, 1] and want to rotate it 3 places:

Create a new array containing the results
Start iterating through the array, calculating the index in the new array and assigning the values
Starts at i = 0 (value 5). Wants a rotation of 3, so newArray[i + k] = array[i]
Continues this up to i = 2, where we find a hitch: newArray[i + k] = array[i], a.k.a. newArray[5] = array[2], so out of bounds. Uh oh!
We must make the assignment cycle around, so we must use mod with the size of the array to produce a single iteration over the initial array with this: newArray[(i + k) % n] = array[i]


You can combine the conditions. It's invalid if both are set: $_REQUEST['b_id'] && $_REQUEST['s_id'] OR if neither are set: !$_REQUEST['b_id'] && !$_REQUEST['s_id']. The intermediary variables are unnecessary.

Additionally, the  tag has been deprecated for some 20 years now and the use of inline styles is discouraged. You should make the element a
 with a class and set the style in CSS, including a text-align: center; rule to get the same effect.

if( ($_REQUEST['b_id'] && $_REQUEST['s_id']) || (!$_REQUEST['b_id'] && !$_REQUEST['s_id']) ) {
    die('
Not A Valid Request URL
');
}


First off, you don't need to explicitly inherit from object when creating classes. In Python 3.x, you can just type class MyClass:, and leave it as that if you aren't inheriting from any other classes.

Secondly, I think your current design is fine, as long as the Screen class implements more methods, and the GameManager as well.

Finally, just a little nitpicky tip, your variables Window, and Game should be renamed to window and game.
Likewise, in Screen, the attributes WIDTH, HEIGHT, SURFACE should be renamed to width, height, surface, respectively.
Actually more than being nitpicky,
these recommendations come from PEP8, the Python style guide.


Your approach takes \$O(n^2)\$ time. Since n can be as large as 100,000, you'll likely need something better. Some benchmarks (inputs are the numbers 1 to n shuffled, and the table shows times in seconds):
     n | original  AJNeufeld  AJ_no_islice  Kelly_Bundy
-------+------------------------------------------------
  1000 |   0.12       0.07          0.06         0.07
 10000 |  11.92       7.98          7.23         0.09
 20000 |  50.82      32.83         29.79         0.11
100000 |      -          -             -         0.18

I didn't run the first three solutions on n=100000, they're too slow. AJ_no_islice is the same as AJNeufeld, except with a regular slice instead of islice to demonstrate that islice is not faster but slower.
My solution in a function that takes a list of numbers and returns the result (much better for testing, and for clarity):
def solve(numbers):
    incs = [0] * 100001
    for numerator, freq in Counter(numbers).items():
        for multiple in range(numerator, 100001, numerator):
            incs[multiple] += freq
    incs = list(accumulate(incs))
    return sum(incs[denominator] for denominator in numbers)

It's similar to the sieve of Eratosthenes, though I mark multiples of all numbers, not just of primes. Runtime is O(n log n).
Consider some numerator, let's say 3. Then for every denominator 3 or higher, it contributes 1 to the total. For every denominator 6 or higher, it contributes 2 to the total. And so on. As a table:
incs = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, ...]
So if you then consider some denominator, let's say 7, you simply look up incs[7] to see that it contributes 2 to the total (with the numerator 3).
Now instead consider some other numerator, let's say 4. Its table is:
incs = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, ...]
Together for numerators 3 and 4:
incs = [0, 0, 0, 1, 2, 2, 3, 3, 4, 5, 5, 5, 7, 7, 7, 8, 9, 9, ...]
How to efficiently compute that table? First only mark the increment spots, e.g., for denominator 3:
incs = [0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, ...]
And for denominators 3 and 4 together:
incs = [0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 2, 0, 0, 1, 1, 0, 1, 0]
And then just accumulate the prefix sums.
Full benchmark code (includes correctness checking):
from timeit import repeat
from random import choices, shuffle
from collections import Counter
from itertools import islice
from itertools import accumulate

def original(numbers):
    numbers = sorted(Counter(numbers).items())
    sigma = 0
    for i in range(len(numbers)):
        for j in range(i, len(numbers)):
            sigma += (numbers[j][0] // numbers[i][0]) * numbers[j][1] * numbers[i][1]
    return sigma

def AJNeufeld(numbers):
    numbers = sorted(Counter(numbers).items())
    sigma = sum((a_j // a_i) * a_j_count * a_i_count
                for i, (a_i, a_i_count) in enumerate(numbers)
                for a_j, a_j_count in islice(numbers, i, None))
    return sigma

def AJ_no_islice(numbers):
    numbers = sorted(Counter(numbers).items())
    sigma = sum((a_j // a_i) * a_j_count * a_i_count
                for i, (a_i, a_i_count) in enumerate(numbers)
                for a_j, a_j_count in numbers[i:])
    return sigma

def Kelly_Bundy(numbers):
    incs = [0] * 100001
    for numerator, freq in Counter(numbers).items():
        for multiple in range(numerator, 100001, numerator):
            incs[multiple] += freq
    incs = list(accumulate(incs))
    return sum(incs[denominator] for denominator in numbers)

funcs = original, AJNeufeld, AJ_no_islice, Kelly_Bundy

# Correctness
numbers = choices(range(1, 100001), k=1000)
expect = funcs[0](numbers)
for func in funcs:
    result = func(numbers)
    print(result == expect, func.__name__,)
print()

# Speed
names = [f' {func.__name__} ' for func in funcs]
print('     n |' + ''.join(names))
print('-------+' + '-' * sum(map(len, names)))
for n in 1000, 10000, 20000, 100000:
    print(f'{n:6} |', end='')
    numbers = list(range(1, n+1))
    shuffle(numbers)
    for func in funcs:
        if n <= 20000 or func is Kelly_Bundy:
            t = min(repeat(lambda: func(numbers), number=1, repeat=1))
            t = '%.2f' % t
        else:
            t = '-'
        print(f'{t:>{len(func.__name__)-1}}   ', end='')
    print()


Code redundancy issue while feeding dropdownlists

It's a small thing, but you could move the bulk of the code for course selection outside of the if statement by initializing the list and then filtering it further only if the user is not an admin.

    studentAssignmentViewModel.Courses = _studentAssignmentService.Courses.ToList();
    studentAssignmentViewModel.CourseSelectListItem = studentAssignmentViewModel.Courses
        .Where(t => (t.Status != Status.Removed)).OrderBy(x => x.Name)
        .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });

    //If the user is not admin, it filter the course list further
    var userId = _dashboardUserAuthenticationService.AuthenticatedDashboardUser.Id;
    var userRole = _dashboardUserService.Get(userId).UserRole;
    if (userRole != "1")
    {
        studentAssignmentViewModel.CourseSelectListItem = studentAssignmentViewModel.CourseSelectListItem
            .Where(t => (t.TeacherId == userId).OrderBy(x => x.Name)
            .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
    }

That may perform slightly worse because now it has to iterate twice if the user isn't an admin, but you're no longer repeating yourself. Any change to the logic would only have to occur in one place.

Now there's this...

  if (userRole != "1")

If you changed this to use an enum instead, that comment becomes obsolete and can be removed. Always try to let the code document itself. I would much rather see this.

if (userRole != UserRole.Admin)

Also, you say you're repeating this logic elsewhere in your code. You've not shown it, but I highly recommend extracting a new class that is responsible for this logic. You can then inject it into these other classes via their constructor and any changes to this logic truly only has to occur in one place.


Some minor style and code comments:

Be consistent in using snake_case for variables names – Most names are good, but then a fileCount and dirCount sneaks in. Also try avoid using abbreviations like fc and dc
Avoid building lists twice – You first build the list of files from  os.listdir(), and then rebuild it using files in combination with print_hidden. This can be avoided using a list comprehension with an if statement like [a for a in a_list if a == something]
Avoid one-time intermediate variables – If you use a variable just once, it can be argued that it is better to just use the expression directly. In your code this applies to padding, filename and prefix
Avoid hiding predefined variables and functions – Don't use reservered words like file in your code, which hides the original file.
When supplying all variables, you don't need to prefix them by name – In your recursive call to tree you prefix them, which is not needed as the order and presences is already stated.
Instead of storing text, store a boolean in your pad_info – To avoid string comparisons and storage, it makes more sense to store a boolean value whether the director is the last in the current directory or not. This can further simplify your code by using a preset list to choose which text to be displayed directly as True = 1 and False = 0 when used in a list context.
Maybe a personal preferences, but use """ for docstrings – If you are consistently using """ for docstrings, this allows for intermediate ' in the text, as well as enabling you to comment out larger portion of code securely using the other option of '''.
Add option to remove output – As your code returns the file and directory counts, it could be viable to foresee a situation where you are not interested in actually viewing the output. This could be added as another option to your function.
Use internal function to hide inner implementation details - It could be argued that this is a good candidate for using a function within the function. This internal function could be the one actually handling the recursion, and only having the parameters path and depth.

In other words, you could hide some of the inner workings of your function using a inner function, and let the outer function be a simple call to the inner function doing the work for you. Notice also that the inner function has full access to the outer functions variables, so need to pass them around (or treat as globals).
BUG: Your code doesnt' respect the max_depth variable – You don't have anything bailing out if the depth is too high...
Feature: No marking of empty directories – If reducing max_depth or having empty directories there is no marking to indicate that the current entry is actually a directory.

My refactored code

Here is the code when applying most of this comment to it:

import os

FOLDER_PATTERN = ['|   ', '    ']
FILE_PATTERN = ['|-- ', '`-- ']

def tree(path, do_output=True, print_hidden=False, max_depth=100):
    """Print file and directory tree starting at path.

    By default, it prints upto a depth of 100 and doesn't print hidden files,
    ie. files whose name begin with a '.'. It can be modified to only return
    the count of files and directories, and not print anything.

    Returns the tuple of number of files and number of directories
    """

    def _tree(path, depth):
        file_count, directory_count = 0, 0
        files = sorted((os.path.join(path, filename)
                           for filename in os.listdir(path)
                           if print_hidden or not filename.startswith('.')),
                       key=lambda s: s.lower())

        files_count = len(files)

        for i, filepath in enumerate(files, start = 1):

            # Print current file, based on previously gathered info
            if do_output:
                print('{}{}{}'.format(
                    ''.join(FOLDER_PATTERN[folder] for folder in parent_folders),
                    FILE_PATTERN[i == files_count],
                    os.path.basename(filepath)))

            # Recurse if we find a new subdirectory
            if os.path.isdir(filepath) and depth < max_depth:

                # Append whether current directory is last in current list or not
                parent_folders.append(i == files_count)

                # Print subdirectory and get numbers
                subdir_file_count, subdir_directory_count = \
                    _tree(os.path.join(filepath), depth+1)

                # Back in current directory, remove the newly added directory
                parent_folders.pop()

                # Update counters
                file_count += subdir_file_count
                directory_count += subdir_directory_count + 1

            elif os.path.isdir(filepath):
                directory_count += 1

            else:
                file_count += 1

        return file_count, directory_count

    parent_folders = []
    return _tree(path, 1)


Use std::filesystem::path for paths

C++17 gives you a canonical type to represent filesystem paths, so use that. This avoids having to create templates of all your functions. It also allows you to combine paths together in a portable way:

void folderLink(std::filesystem::path &setDisplayName, std::filesystem::path &getDisplayName)
{
    getDisplayName = setDisplayName / getDisplayName;
    ...
}

Use std::filesytem::create_directories()

This function will create the desired directory plus all its parent directories if they do not yet exist. Also, it will not report an error if the desired directory already exists. So you could write:

void foldersystem()
{
    std::filesystem::path folder_Documents = ...; // get known folder as a path here

    std::filesystem::create_directories(folder_Documents / "Microsoft" / "XP" / "Alpha");
    std::filesystem::create_directories(folder_Documents / "Microsoft" / "XP" / "Beta");
    std::filesystem::create_directories(folder_Documents / "Microsoft" / "Win7" / "Alpha");
    std::filesystem::create_directories(folder_Documents / "Microsoft" / "Win7" / "Beta");
}

Don't infinitely retry on errors

You are using a very weird pattern with infinite for-loops:

for(;;) {
    if (something_fails())
        continue;

    break;
}

If the thing you are trying to do fails, you are retrying it indefinitely. But if it fails once, why do you expect it will work the next time? The right thing to do at this point is just to return an error.

Prefer returning results instead of using output parameters

If a function returns something, return that instead of passing a reference to an output parameter. Combined with the use of std::filesystem::path, knownFolder() then becomes:

std::filesystem::path knownFolder(KNOWNFOLDERID fodlerID)
{
    PWSTR pszFolderPath;

    if (FAILED(SHGetKnownFolderPath(folderID, 0, nullptr, &pszFolderPath)))
        throw std::runtime_error("Could not get known folder");

    std::filesystem::path result = pszFolderPath;
    CoTaskMemFree(pszFolderPath);
    return result;
}

Use an array of paths if you have many of them

If you have many paths to create, then store them in an array, and use a for-loop to create them all. Here is an example:

static const std::filesystem::path required_subdirectories[] = {
    "XP/Alpha",
    "XP/Beta",
    "Win7/Alpha",
    "Win7/Beta",
};

void foldersystem()
{
    std::filesystem::path folder_Documents = ...; // get known folder as a path here

    for (auto &subdirectory: subdirectories) {
            std::filesystem::create_directories(folder_Documents / "Microsoft" / subdirectory);
    }
}

Note that using the forward slash is perfectly fine here; the std::filesystem functions understand this as a directory separator.


Efficient mechanism to generate operator overload functions

I was looking a bit at your PyCXX and want to offer you Barton–Nackman trick using Curiously recurring template pattern together with variadic template recursion (through partial specialization). This way you can solve all your types and conversion operators with one template:

template<typename T> struct Arithmetic;
using Long = Arithmetic<long long>;
using Double = Arithmetic<long double>;

template<class Base, class... Other> struct compare_operators {};

template<class Base, class First, class... Other>
  struct compare_operators<Base, First, Other...>
  : compare_operators<Base, Other...>
{
    friend bool operator == (const Base& a, First b) {
        return a.template as<First>() == b; }
    friend bool operator != (const Base& a, First b) {
        return a.template as<First>() != b; }
    friend bool operator <  (const Base& a, First b) {
        return a.template as<First>() <  b; }
    friend bool operator <= (const Base& a, First b) {
        return a.template as<First>() <= b; }
    friend bool operator >  (const Base& a, First b) {
        return a.template as<First>() >  b; }
    friend bool operator >= (const Base& a, First b) {
        return a.template as<First>() >= b; }

    friend bool operator == (const Base& a, const Arithmetic<First>& b) {
        return a.template as<First>() == b.value; }
    friend bool operator != (const Base& a, const Arithmetic<First>& b) {
        return a.template as<First>() != b.value; }
    friend bool operator <  (const Base& a, const Arithmetic<First>& b) {
        return a.template as<First>() <  b.value; }
    friend bool operator <= (const Base& a, const Arithmetic<First>& b) {
        return a.template as<First>() <= b.value; }
    friend bool operator >  (const Base& a, const Arithmetic<First>& b) {
        return a.template as<First>() >  b.value; }
    friend bool operator >= (const Base& a, const Arithmetic<First>& b) {
        return a.template as<First>() >= b.value; }
};

template<typename T> struct Arithmetic
  : compare_operators<Arithmetic<T>
  , long long, int, short, double, float, long double>
{
    T value;
    Arithmetic(T value): value(value) {}

    template<typename X, typename = enable_if_t<is_arithmetic<decay_t<X>>::value>>
      X as() const { return (X)value; }
};

int main() {
    Long val(3);
    if(val > 2) cout << "val > 2\n";
    if(val <= 3.2) cout << "val <= 3.2\n";
    Double dbl(3.14);
    if(val < dbl) cout << "val < dbl\n";
}

Beware that the comparision operators need some fine-tuning especially when you compare integral vs. floating-point (which to choose as common type) and that dacay_t in conversion operator may be problematic (not sure). (Finally imagine using namespace std, but I use my own header while explicitly using selected std features/classes in the namespace and then using the namespace).

BTW: This would be the same (but the as conversion is altered) in my own syntax, which you may find a bit familiar:

#include "basics.hpp"
using*firda

forward template<typename T> struct Arithmetic
using Long = Arithmetic<long long>
using Double = Arithmetic<long double>

template<class Base, class... Other>
  struct compare_operators

template<class Base, class First, class... Other>
  struct compare_operators<Base, First, Other...>
  : compare_operators<Base, Other...>

    friend bool operator == (const Base& a, First b)
        return a.template as<First>() == b
    friend bool operator != (const Base& a, First b)
        return a.template as<First>() != b
    friend bool operator <  (const Base& a, First b)
        return a.template as<First>() <  b
    friend bool operator <= (const Base& a, First b)
        return a.template as<First>() <= b
    friend bool operator >  (const Base& a, First b)
        return a.template as<First>() >  b
    friend bool operator >= (const Base& a, First b)
        return a.template as<First>() >= b

    friend bool operator == (const Base& a, const Arithmetic<First>& b)
        return a.template as<First>() == b.value
    friend bool operator != (const Base& a, const Arithmetic<First>& b)
        return a.template as<First>() != b.value
    friend bool operator <  (const Base& a, const Arithmetic<First>& b)
        return a.template as<First>() <  b.value
    friend bool operator <= (const Base& a, const Arithmetic<First>& b)
        return a.template as<First>() <= b.value
    friend bool operator >  (const Base& a, const Arithmetic<First>& b)
        return a.template as<First>() >  b.value
    friend bool operator >= (const Base& a, const Arithmetic<First>& b)
        return a.template as<First>() >= b.value

template<typename T> struct Arithmetic
  : compare_operators<Arithmetic<T>
  , long long, int, short, double, float, long double>

    T value
    Arithmetic(T value): value(value) {}

    template<typename X>
      enable_if_t<is_arithmetic<X>::value,
      X> as() const
        return value

int main()
    Long val(3)
    if val > 2; cout << "val > 2\n"
    if val <= 3.2; cout << "val <= 3.2\n"
    Double dbl(3.14)
    if val < dbl; cout << "val < dbl\n"


You didn't post your HTML, but the element with the id searchBtn doesn't seem to be a button, so it shouldn't be called "btn" in it's id or variable name.
There are many variables that don't change their value, so you should be using const instead of let (or var).
The variables arr and searchKeyword are only used inside the event handler, so they should be declared in there and not outside.
The function getUserAsync doesn't use its parameter.
You should use the event input instead of keyup, because the value of the input can change without a keypress.
The same .replace calls are used on the keywords and the content being searched, so that should be extracted into their out function.
The requirement that only the first keyword must be longer than two characters seems a bit arbitrarily. The user won't get any results, even if there are more valid (longer) keywords, but they will get results from invalid (shorter) keywords if they are not in the first position. It probably would make more sense to filter out words shorter than three out of the list of keywords.
Using a deconstructing assignment to create variables that you don't use and in order to exclude certain object properties seems strange. It would probably make more sense to do something like:
const IGNORED_PROPERTIES = ["id", "DeptUrl", "pid" /* etc. */ ];
const elCompind = Object.entries(el)
  .filter(([k, v]) => !IGNORED_PROPERTIES.includes(k))
  .map(([k, v]) => v)
  .join()
  /* etc. */;

The expression checkAllWords.includes(false) ? false : true can be simplified to !checkAllWords.includes(false), however it is not necessary at all, because instead of mapping all keywords to a boolean and then checking of there is a false item, you can use the .every array method. This also has the advantage, that it will stop once a single false has been found and won't necessarily check more keywords:
return searchKeyword.every(item => elCompind.includes(item)});

(Also notice the simplified lambda.)


Validating that all strings in an array match a condition

Yes, return immediately* returns from the method, no matter where in the method you are. You don't need the break.

But there is even easier way to write this code, using the LINQ method All():

strs.All(str => str == condition)

This also returns as soon as single non-matching element is found and is more readable.

* Actually, finally blocks run before you actually return from the method, but that's not relevant here.


Pattern matching in an array or collection

You are unnecessarily looping through the array 3 times (only one loop is required). Its not clear how you will be using the results, but assuming you need to store them, then the code can be simplified to

int[] array = new int[15] { 1, 0, 1, 2, 0, 1, 0, 1, 0, -1, 0, 2, 0, -2, 0 };
// Define 3 lists from the results
List<int> all = new List<int>();
List<int> up = new List<int>();
List<int> down = new List<int>();
// Get the index of the first zero value and add to the lists
int first = Array.IndexOf(array, 0);
all.Add(first);
up.Add(first);
down.Add(first);
// Loop the remaining items in the array and add to the appropriate lists
for (int i = first + 1; i < array.Length; i++)
{
    int current = array[i];
    int previous = array[i - 1];
    if (current != 0)
    {
        continue;
    }
    if (Math.Abs(previous - current) > 1)
    {
        all.Add(i);
        if (previous - current > 1)
        {
            up.Add(i);
        }
        else if (previous - current < 1)
        {
            down.Add(i);
        }
    }
}

The result is

all contains [1, 4, 12, 14], up contains [1, 4, 12] and down contains [1, 14]


Storing singleton instances in a generic utils class

Let me just express the first thing that came to mind when I read this question's title:

  Not another Singleton question.

Let's ignore in the following that Singletons are an anti-pattern in Object-Oriented Programming.

Look. I get it. Singletons are nice and easy.
Everything about them makes things easier to think about.
The whole point of a singleton is that only one instance of it ever exists.
It's by definition the single source of truth.

What your code does is subtly, but completely undermine that assumption.

Consider the following sequence:

AuthManager authSingleton = AuthManager.getNewInstance();
SingletonUtils.removeInstance(AuthManager.class),
AuthManager anotherSingleton = AuthManager.getNewInstance();

Those don't need to be in the same thread, the same class or the same anything. As long as they run in the same JVM, authSingleton == anotherSingleton will be false. And this is a complete and utter breakage of the semantics of a Singleton.

What you tried to do with that class is not something that you want. You're centrally controlling the lifetime of singletons. But you're not correctly enforcing the semantics of these singletons.

This code is something like an ObjectPool. Implying that it has anything to do with singletons is incorrect though.

Do not make singletons complicated:

public final class AuthManager {
    private static final AuthManager INSTANCE = new AuthManager();
    public static AuthManager get() {
        return INSTANCE;
    }

    private AuthManager() {
    }
}

^^ This is a complete, threadsafe and lazily initialized Singleton. In 99.9999% of the use-cases of a singleton, this is enough. But 90% of all Singleton uses are just flat out wrong.

There is no useful reason for an "AuthManager" to be a Singleton. Don't cargo-cult.


The for loop seems fine to me; it isn't abusing any semantics. The semantics of the for loop are quite clear:

for (initialization; loop condition; increment)

Anyone who doesn't know this off the top of their head probably doesn't know the language as well as they think they do. Although you could have written this code using a while loop, it's just a matter of opinion whether that is better. In general, you can transform any for loop into a while loop. When I write a "complex" for loop, I tend to prefer to break each of these components into separate lines for readability (and also to keep the line from getting too long).

However, using the return value of printf the way you did is just wrong. It returns a negative value if the operation failed. You are adding arbitrary positive and negative return values together and checking to see whether the result is non-zero. That is incorrect, and thus decidedly unclever.

You could might say that the test condition could be modified to j > 0, but that's still not precisely correct because one of the printf calls might succeed and return, say, 5, while the other one might fail and return −5. Should the number be printed, or not?

So, while I have no problem with your choice to use a for loop here, I do not like what you've done in the body of that loop. I disagree with cHao's comment that this would be an instant no-hire. I'd probably assume you were a competent programmer and having fun with the inherently-boring FizzBuzz problem. However, I would expect you, with a bit of prompting, to see and begin to explain some of the problems with your chosen approach.

Aside from that…

Keep in mind that code does not become more efficient just because you reduce the number of apparent instructions that you write in C. Optimizing compilers do not perform a literal translation of C instructions into assembly instructions. And even non-optimizing compilers may not be able to do so if they wanted to, because there isn't necessarily a 1-to-1 correspondence of instructions in both languages.

In this case, you're not even gaining any efficiency with the way you've written the printf statements. In fact, the execution of printf is by far the slowest part of the program, so by any real-world performance metrics, avoiding calls to printf whenever possible would be the way to boost performance. Certainly it is not a win to replace a reasonably well-predicted conditional branch with an expensive and pointless function call!

In fact, if you weren't trying to be overly clever, you could substitute puts for printf where you were outputting constant "Fizz" and "Buzz" strings, which would be even more efficient. (Some compilers like GCC will do this translation for you when they can, but they wouldn't be able to do it with the way you'd originally written the code, obviously.)
Stylistically, I would prefer that you kept the variables to as narrow a scope as possible. Since at least C99, you have been allowed to declare variables within a for loop's scope, and this is what I would recommend that you do.
Even more importantly, I prefer to see that variables are initialized at the point of their declaration whenever possible. It bothers me to see lines like:

int i, j;
i = j = 0;

I don't like the attempt to combine initialization of multiple variables onto one line, either. Break them up into two lines. No excuses.


I think you're pretty close to optimal here. I made a few tweaks, to avoid some conditionals by using sets instead. I don't actually know if it'll run faster; you'll need to benchmark it, and it likely depends on the breakdown of how many dupes per county there are.

def get_codes3(data):
    from collections import defaultdict
    codeinfo = defaultdict(set)
    for row in data:
        county = row["county"]
        # remove float() if you can get away with it - are there
        # actually values like '1.5' in the data?
        code = int(float(row["code"]))
        if code > 100000:
            code = code/100

        codeinfo[county].add(code)
    # if you can get away with sets instead of lists in your return
    # value, you're good
    return code_info
    # otherwise:
    # return dict([(county, list(info)) for county, info in code_info.iteritems()])

You don't need float() unless the data is actually like "123.45" - it's not clear if that's the case
sets can work in most places that lists work, so you might not need to convert to a list
It might be worth it to write a script that does just the x = x/100 if x > 100000 part and writes that out to a new file


Calculation of elasticity for non-linear curve

I'll provide feedback from top to bottom:

1. elasticity<-function(y.p,x.p,band){

It's recommended to use spaces to make your code easier on the eyes. Spaces also avoid ambiguous situations for people who are not experts in R's syntax rules; for example, when someone sees a<-b, is it assigning b to a, or is it asking if a is less than -b? Maybe another way to convince you is to make you notice that R's compiled code does contain spaces (run print(lapply) for example); it shows that R's authors agreed that code readability was more important than compactness.

Now about the choice of arguments. Why not use the same argument names (and order) as locpoly since it is the main function being called here? So I'd recommend x, y, bandwidth. Or maybe x.price, y.price, bandwidth if it really helps knowing these are prices.

2. require(KernSmooth)

To convince you to use library instead of require, check http://www.r-bloggers.com/library-vs-require-in-r/.

3. as.vector(y.p);as.vector(x.p)

These two calls to as.vector do nothing if you do not assign the output. You probably meant to do:

y.p <- as.vector(y.p)
x.p <- as.vector(x.p)

11. y1<-as.vector(loess.der$y)

If you check using is.vector(), you will see that loess.der$y is already a vector, so as.vector is unnecessary.

12. eps<-matrix(NA,length(y.p),2)

Would a data.frame make more sense? Or if you really want a matrix, should use be using cbind?

14. for(i in 1:length(y.p)){
15.    eps[i,2]<-x.p[i]/y.p[i]*y1[i]
16. }

Here, you are really missing up on vectorization. This should be:

eps[, 2] <- x.p / y.p * y1

Overall, if defining a data.frame, appreciate the simplicity and readability of:

eps <- data.frame(Price = x.p,
                  Elasticity = x.p / y.p * loess.der$y)

Or if you want a matrix, just replace data.frame() with cbind().

Taking all of my comments into account, your code could look like this:

elasticity <- function(x, y, bandwidth) {
   library(KernSmooth)
   x <- as.vector(x)
   y <- as.vector(y)
   loess.fun <- locpoly(x = x, y = y, bandwidth = bandwidth)
   plot(loess.fun, type = 'l', lwd = 2, lty = 4,
        ylim = c(0, 100), xlab = "Price", ylab = "Share", col = 2,
        main = "Local Polynomials Estimation")
   loess.der <- locpoly(x = x, y = y, drv = 1, bandwidth = bandwidth,
                      gridsize = length(y))

   eps <- data.frame(Price = x,
                     Elasticity = x / y * loess.der$y)

   return(eps[order(eps$Price), ])
}


YouTube playlist steganography: hide secret messages inside YouTube playlists

Style

In any significant project, especially one that you are sharing through GitHub, it is important to write docstrings for each function.  You haven't written any.

It is implied by the PEP 8 official style guide that functions should be named using lower_case_with_underscores and constants should be named using UPPER_CASE_WITH_UNDERSCORES.  I would recommend renaming BITARRAY → BIT_ARRAY and getsum() → get_sum(), because pythonisnotgermanorfinnish.

Implementation

Whenever you build a list by starting with an empty list and appending to it in a loop, you'll almost certainly want to write a list comprehension or a generator expression instead.  That way, you describe the result "all at once" using a single statement.

from string import digits, ascii_uppercase, ascii_lowercase

INIT_CHARS = '-' + digits + ascii_uppercase + '_' + ascii_lowercase
FINAL_CHARS = '048AEIMQUYcgkosw'
BIT_ARRAY = sum(([tuple((a, b)) for a in INIT_CHARS] for b in FINAL_CHARS), [])

The sum() function above is used to concatenate lists.  That expression is a bit nasty.  You can write it better using itertools.product(), which is exactly what we need:

from itertools import product
from string import digits, ascii_uppercase, ascii_lowercase

INIT_CHARS = '-' + digits + ascii_uppercase + '_' + ascii_lowercase
FINAL_CHARS = '048AEIMQUYcgkosw'
BIT_ARRAY = list(product(INIT_CHARS, FINAL_CHARS))

Note, however, that it would be better not to define your BITARRAY at all, if your only goal is to find the index of a particular pair of characters.  Instead of BITARRAY.index(…), it would be more efficient to do a little arithmetic:

def numeric_value(init_char, final_char):
    """
    Given character init_char (one of the characters [-0-9A-Z_a-z]) and
    character final_char (one of the characters [048AEIMQUYcgkosw]),
    deterministically produce a numeric value from 0 to 1023, inclusive.
    """
    return INIT_CHARS.index(init_char) * len(FINAL_CHARS) + \
           FINAL_CHARS.index(final_char)

Based on similar principles, I would write this function:

def get_sum(video_ids):
    """
    Compute a tuple of numbers for the given YouTube video IDs.

    The videos IDs are taken two at a time.  From each pair, the initial
    character of the first ID and the final character of the second ID are
    taken.  Those two characters are mapped a numeric value between 0 and 1023.

    If there are an odd number of video IDs, the last one is ignored.
    """
    return tuple(
        numeric_value(a[0], b[-1]) for a, b in zip(*[iter(video_ids)] * 2)
    )

The zip(*[iter(video_ids)] * 2) expression above is a slick way to split the video_ids into pairs.  It comes from the grouper() example in the itertools recipes.

Note that your original getsum(addrlist) function is actually equivalent1 to

def getsum(addrlist):
    return [get_sum(playlist) for playlist in addrlist]

I recommend splitting the work this way instead, so that you don't end up with an excessively nested list comprehension.

1 Well, it's not exactly equivalent, in that your BITARRAY lookup silently ignores pairs of characters that do not conform to the ([-0-9A-Z_a-z], [048AEIMQUYcgkosw]) scheme, whereas numeric_value(…) would raise a ValueError.


Is this a good way of managing parallel go routines when I care about ordering of results?

The answer to "Can I be sure...?" is no, there is nothing in your code that ensures that.  That is why results sometimes go missing.

Missing results are a sign of a data race.  You can use the Go race detector to find and fix these problems.  Data races are categorically dangerous.  They can corrupt memory.

You might be able to find and fix the problem by adding more synchronization, but your code is too complex as it is.  Since you asked, a pattern you should probably be using is a particular producer-consumer pattern.  It has two parts, 1) a producer goroutine that sends data to a channel and closes the channel after sending the last value, and 2) a consumer goroutine with a for loop that ranges over the channel.  With this pattern you should be able to dispense with the select statement, the stage complete channel, and the control routine wait group.

Your code that begins for i, some_data := range my_data is what I'm calling a producer.  It produces data on the channel stage_one_channel.  Following wg.Wait(), you should replace the line stage_complete <- true with close(stage_one_channel).

Replace your for loop containing the select statement with a separate for loop for each stage, something like

for new_stage_one_results := range stage_one_channel {
    ...
}

When this for loop completes, you are sure that all data has been received from stage_one_channel and processed by the loop body.  This is the synchronization your code is missing.  Your current mechanism only waits for data to be sent, not received and processed.

When the last loop completes, your program can exit.  You could retain some of your mechanism for waiting for this, but simpler would be swap what you currently have in your main goroutine for the "consumer" code that you currently have in that first function literal.  That is, run your producers in one or more separate goroutines so you can have your consumers--the last one especially--in main.  When the last consumer has processed the last data, you know your program is done, with nothing else to wait for.

Finally, let me reinforce, if go run -race says you have a problem, you have a problem.


Coding style

Please follow PEP8, the style guide for Python code.
As you read through it, you should recognize several coding style violations in your posted code.
There is also a command line tool called pep8, which can check your entire project and report the violations. You can install it with:

pip install pep8

Strange condition

This looks very strange:

return values is not False and all(unitsolved(unit) for unit in unitlist)

From the posted code it's not clear what is the type of values.
The plural name implies some kind of collection,
but then it can never be False.
As such, this condition doesn't make sense.


Counting the triangles that can be formed from segments of given lengths

The statement V.push_back(temp); can be inefficient, as the vector V may need to be reallocated multiple times.

Use std::vector::reserve(N) to ensure sufficient space exists in the vector before reading in the data to avoid multiple reallocations.

  \$3 \le N \le 10^7\$
  \$1 \le \mathrm{arr}[i] \le 10^3\$

With \$10^7\$ pigeons and \$10^3\$ holes, many holes can have over 10,000 pigeons!  You might want to consider an array of counts indexed by side length.  No sort required; it is automatically sorted.  But your algorithm will need considerable reworking.


Take items directly from the thing, without indexing:

x = [arr !! digitToInt i | i <- input]

And prefer where over let: (where is so much more common than let, it is easier to read as you see the general picture before the details.)

newFunction input = sum [arr !! digitToInt i | i <- input]
  where
    arr = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]

arr is a bad name, I would prefer dashesInDigits

assert should be more general (take f as argument) and written using guards.


Parsing a String to see if it contains another String, and then returning a monad if it does

Why do you need the element type to be a monad? The only point you require it is when you do return () in order to signal failure. I'd propose implementing a more general function

lookupSublist :: Eq a => [a] -> [([a], b)] -> Maybe b

Which could be implemented as:

lookupSublist xs = fmap snd . listToMaybe . filter (flip isInfixOf xs . fst)

So we first filter out all alternatives where the first element doesn't have xs as infix. Then we return the second element of the first remaining element, if any.

Some random notes on your code:

Using noEmptyList as a guard mid-expression isn't a good idea. Using error is pretty "evil" in the first place, you don't want to bury it like that. Putting the list in the where would allow you to say listenString a l | null list = error...
(\(x,_) -> if (x == []) then False else True) is simply not . null . fst. I'm not quite sure why you filter for that, to be honest. Wouldn't having [] in the list be a pretty elegant way to implement a default fallback value?
I am actually quit struggling to understand the rest of your code. I am pretty sure that your usage of ListT actually hurts more than it helps - generally when you start pattern-matching on the contents of a monad you are doing something wrong. Could you explain what you tried to do?

Edit: If the position of the match end should take priority, I would propose going over the prefixes of the string and suffix-test the options:

lookupFirstSublist str opts = listToMaybe $ mapMaybe f $ inits opts
  where f s = fmap snd $ listToMaybe $ filter (flip isSuffixOf s . fst) opts


Create player according to chosen difficulty

There are several things that can be improved, in my opinion:

Whitespaces around operators make the code more readable (you use them almost everywhere except this method):

public String toString() {
    return "play \t" + position + "\t" + stepsLeft + "\t"
           + jokingSkill + " \t" + score + "\n";
}

Comments like // VARIABLES ---------- or // METHODS ---------- are useless (they do not contain any additional information). Adding comments for each individual method explaining what it does (especially for public ones) or what a field is used for is a good practice.
An alternative for using switch statement is creating an array of constants. It can look like this:

private static int[] stepsLeftForLevel = new int[]{150, 150, 100, 10};

...

public Player(Position position, int difficultyLevel) {
    ...
    stepsLeft = stepsLeftForLevel[difficultyLevel];
    ...
}

It makes the code more readable in my opinion because all "magic" numbers are located in one place (and the code becomes more concise).
There is no need to use this in a constructor unless the name of the field is shadowed by a parameter (that is, I would recommend using this only when it is necessary).


To begin with, you don't need list_n at all: a decision that the number is composite can be made on the fly, as soon as some remainder becomes 0. If none of them were 0, you know that the number is prime:

    for n in range(2, x):
        if x % n == 0:
            return False
    return True

is effectively what your code is doing, but without the list, and without special case for 2.

That said, of course the algorithm could be greatly improved, but it is beyond the point of this exercise.


User registration - Controller, service and repository layers in Spring framework

Should I keep in my Controller class just AuthService field? I'm using userRepository to check if username and email is available.

I think it is ok to use the UserRepository directly, but that is a matter of taste. You could create an additional UserService to wrap the calls to the UserRepository, or you could also create these wrapping methods in your AuthService.

Example:

public class UserService/AuthService {

   private UserRepository userRepository;

   public boolean userExistsByUsername(String username) {
       return userRepository.existsByUsername(username);
   }
}

Then you can use these UserService/AuthService methods in your controller.

For me, at this point, this looks like an unnecessary indirection, but this is the classic way of dividing layers.

  In AuthService should I keep just authRepository and other services
  fields? Currently I'm using there RoleRepository.

Same answer as for question 1. You could write a RoleService class which wraps the RoleRepository calls.

  Is return type in my controller a good practise? ApiRespose is two-field class.

I think that's totally ok, because you want to set different HTTP status codes.

Other things:

HTTP status code

new ApiResponse(false, "Username is already in use!"), HttpStatus.BAD_REQUEST);

Just a hint, the correct HTTP status code for existing entities is 409, so I would use HttpStatus.CONFLICT. But 400 is also ok.

Exception handling

This code

Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
        .orElseThrow(() -> new AppException("User Role not set."));

is not inside a try-catch block so if this exception is not handled in another way by a @Provider or some @ExceptionHandler, you may improve this part. If you handling it globally, everything is fine.


Enumerating processes without enumerating flaws of the API

Apart from a performance question regarding ADODB recordsets, I only made one real change to your code. Since there are several fields that are output by the tasklist utility, I would want to capture all of that data just in case I need to expand my database at a later time. So I created a class called OSTask which accepts a single line from the tasklist output and parses it into its component parameters. (This means I could also skip the case you have to calculate column widths.)

Class OSTask

Option Explicit

Private Type InternalData
    ImageName As String
    PID As Long
    SessionName As String  'could also be an Enum: Console, Services
    SessionNumber As Long
    MemUsage As Long
End Type
Private this As InternalData

Public Property Get ImageName() As String
    ImageName = this.ImageName
End Property

Public Property Get PID() As Long
    PID = this.PID
End Property

Public Property Get SessionName() As String
    SessionName = this.SessionName
End Property

Public Property Get SessionNumber() As Long
    SessionNumber = this.SessionNumber
End Property

Public Property Get MemUsage() As Long
    MemUsage = this.MemUsage
End Property

Public Sub Init(ByVal taskData As String)
    '--- converts a single line output from the Windows command
    '    shell utility 'tasklist' and parses the data into the
    '    class properties
    Dim pos1 As Long
    Dim pos2 As Long

    '--- find the end of the task name, looking for double-space
    pos1 = InStr(1, taskData, "  ", vbTextCompare)
    this.ImageName = Trim$(Left$(taskData, pos1))

    '--- the next value is a number followed by a single space
    Dim i As Long
    For i = pos1 To Len(taskData)
        If Not Mid$(taskData, i, 1) = " " Then
            pos2 = InStr(i, taskData, " ", vbTextCompare)
            this.PID = CLng(Mid$(taskData, i, pos2 - i))
            Exit For
        End If
    Next i

    '--- next value is the session name
    pos1 = pos2 + 1
    pos2 = InStr(pos1, taskData, " ", vbTextCompare)
    this.SessionName = Trim$(Mid$(taskData, pos1, pos2 - pos1))

    '--- the next value is a number followed by a single space
    For i = pos2 To Len(taskData)
        If Not Mid$(taskData, i, 1) = " " Then
            pos2 = InStr(i, taskData, " ", vbTextCompare)
            this.SessionNumber = CLng(Mid$(taskData, i, pos2 - i))
            Exit For
        End If
    Next i

    '--- next value is the memory usage, a large number in thousands
    pos1 = pos2
    pos2 = InStr(pos1, taskData, "K", vbTextCompare)
    Dim memUsageText As String
    memUsageText = Mid$(taskData, pos1, pos2 - pos1)
    memUsageText = Replace$(memUsageText, ",", vbNullString)
    this.MemUsage = CLng(memUsageText) * 1000
End Sub

All of the properties are read-only in this case by design.

For my example, I converted your function to return a Collection rather than an ADODB.Recordset just to make my own testing simpler. So the only real change is in the Else case of the Select statement.

For my own learning purposes, I reviewed this answer's detailed review of the command shell interactions. Since you specifically stated that you are avoiding disk I/O, the option to pipe the output to a windows temp file is no good. To really prevent the command shell pop-up, you'd have to go with running a cscript under a wscript shell as the poster there indicates. Additionally, I couldn't find any historical information that the tasklist output has changed over time, so I believe your approach should remain viable across different Windows versions.

Here is my main module with my minor edits for testing:

Option Explicit

Sub test()
    Dim taskList As Collection
    Set taskList = EnumProcesses

    Dim task As Variant
    For Each task In taskList
        Debug.Print task.ImageName & ", " & task.MemUsage
    Next task
End Sub

Public Function EnumProcesses() As Collection
    Dim WshShell As IWshRuntimeLibrary.WshShell
    Dim WshExec As IWshRuntimeLibrary.WshExec
    Dim StdOut As IWshRuntimeLibrary.TextStream
    Dim Data As Collection
    Dim Output As String
    Dim ColumnLengths() As Long

    Set WshShell = CreateObject("WScript.Shell")
    Set WshExec = WshShell.Exec("tasklist")
    Set StdOut = WshExec.StdOut

    Set Data = New Collection

    Do While WshExec.Status = WshRunning
        If Not StdOut.AtEndOfStream Then
            Output = StdOut.ReadLine
            Select Case True
                Case Len(Output) = 0, _
                     Output Like "Image Name*"
                    'Skip
                Case Output Like "====*"
                    'Skip
                Case Else
                    Dim thisTask As OSTask
                    Set thisTask = New OSTask
                    thisTask.Init Output
                    Data.Add thisTask
            End Select
        End If
    Loop

    Set EnumProcesses = Data
End Function


Mapping a file system to a tree structure

Normally, I'd suggest trying to get rid of as much mutable state as possible. That's not really possible here, the circular reference to the parent pretty much guarantees that something is going to need to be mutable.

Vanilla Version

Without deviating much from your original design, there are a few cleanup suggestions that I can make.

First, as suggested by @Carcigenicate , getTree could use some naming fixes. In the version below I used loop, but it could have been any number of choices. I also inlined the creation of rootNode.

  def getTree(pathToRoot: String): Node = {
    def loop(file: File, parent: Node) : Node = {
      val self = Node(file.getName, Some(parent))
      parent add self
      if (file.isDirectory) file.listFiles().foreach(child => loop(child, self))
      self
    }

    loop(new File(pathToRoot), Node("test", Option.empty))
  }

Along those same lines, printNode became printTree because that's really what it does. I also moved the helper functions into Node's companion object. It's a good default organization strategy.

Node itself had mostly structural changes.

I changed the visibility of children, so that mutating it has to pass through the helpers. It also became a Set, as the OS doesn't generally make guarantees about listing order, so I wanted to avoid implying that the order was something that could be relied on not to change.

getChildren became just children and passes a defensive copy of the internal set.

That gives us this final version, with a small driver to make testing easier.

case class Node(name: String, parent: Option[Node]) {
  private[Node] val _children : mutable.Set[Node] = mutable.Set[Node]()

  def addChild(child: Node): Unit = _children += child
  def removeChild(child: Node): Unit = _children -= child
  def children: Set[Node] = Set(_children.toSeq:_*)
}

object Node extends ((String, Option[Node]) => Node) {

  def getTree(pathToRoot: String): Node = {
    def loop(file: File, parent: Node) : Node = {
      val self = Node(file.getName, Some(parent))
      parent addChild self
      if (file.isDirectory) file.listFiles().foreach(child => loop(child, self))
      self
    }

    loop(new File(pathToRoot), Node("test", Option.empty))
  }

  // simple test
  def printTree(node: Node, indent: String = "") : Unit = {
    println(indent + node.name)
    node.children.foreach(printTree(_, indent + "  "))
  }
}

object FileSystemTree {
  def main(args: Array[String]): Unit = args.foreach(arg => {
    Node.printTree(Node.getTree(arg))
  })
}

Lazy Version

It's possible to build a tree in a tail-recursive manner. It's much more difficult to do that with the references to the parent node.

So I cheated by making it a lazy data structure instead.

The first version was pretty basic.

case class Node(file: File, parent: Option[Node]) {
  lazy val children: Set[Node] =
    if (file.isDirectory) file.listFiles().map(f => Node(f, Some(this))).toSet
    else Set()
}

With each node only building the list of children on demand, the getTree function became a one-liner.

object Node extends ((File, Option[Node]) => Node) {
  def getTree(pathToRoot: String): Node = Node(new File(pathToRoot), None)
}

This sacrifices quite a bit of functionality to pull this off, mainly because of my preference for vals. To add the ability to add/remove child nodes, I went with a view instead. This way the data itself stays the same, just our view of it changes.

I also added a helper to provide depth-first traversal, to abstract away doing things with the nodes in the tree.

import java.io.File

case class Node(file: File, parent: Option[Node]) {
  private var filter = (x: Node) => true

  private lazy val _children: Set[Node] =
    if (file.isDirectory) file.listFiles().map(f => Node(f, Some(this))).toSet
    else Set()

  def children: Set[Node] = _children.filter(filter)

  def withFilter(p: Node => Boolean): Node = {
    filter = p
    this
  }

  def foreachDepthFirst(f: (Node, Int) => Unit, depth: Int = 0): Unit = {
    f(this, depth)
    children.foreach(_.foreachDepthFirst(f, depth + 1))
  }
}

object Node extends ((File, Option[Node]) => Node) {
  def getTree(pathToRoot: String): Node = Node(new File(pathToRoot), None)
  def printTree(root: Node): Unit = root.foreachDepthFirst({
    case (Node(f, _), depth) => println(("  " * depth) + f.getName)
  })
}

object FileSystemTree {
  def main(args: Array[String]): Unit = args.foreach(arg => {
    Node.printTree(Node.getTree(arg))
  })
}


Mongoose / MongoDB schemas for blog posts and authors

You can use the forEach function like this

const allPosts = [];

Author.find({}, function(err, users) {
    if (err) throw err;

    users.forEach(function(user) {
        const a = user.posts;
        a.forEach(us => allPosts.push(us));
    });
});

Now the allPosts array will have all the posts.


java Thread-safe LRUCache implementation

Advice 1

This implementation is not thread safe. For example, if two threads invoked getElement(key1) simultaneously, they may runs to concurrentLinkedQueue.add(key) at same times(they both performed delete and get, but delete will fail the second time or just do nothing), then two same keys will be added.

Advice 2

Maybe capacity is more suitable than maxSize.

Advice 3

LinkedHashMap is often used as LRU cache.


You should care about prime factors. Take the prime factors of one to ten, and 2520:

1: none
2: 2
3: 3
4: 2, 2
5: 5
6: 2, 3
7: 7
8: 2, 2, 2
9: 3, 3
10: 2, 5
2520: 2, 2, 2, 3, 3, 5, 7

You should notice that each prime factor appears in all the divisors. So, 2520 is divisible by 8, as it contains the factors 2, 2, and 2.
The remainder will be the product of 3, 3, 5, and 7.

And so you should make a naive prime factors function. After that, you want to get the prime factors of the divisors, and make a dictionary of prime factors for the smallest multiple of the divisors.

Where a simple solution such as the following, is 20000 times faster than the code in your question.

import collections
from operator import mul
from functools import reduce

def prime_factors(num):
    div = 2
    while num > 1:
        if num % div:
            div += 1
            continue
        yield div
        num /= div

def gen_smallest_divisable(divisors):
    factors = collections.defaultdict(int)
    Counter = collections.Counter
    for divisor in divisors:
        div_factors = Counter(prime_factors(divisor))
        for number, amount in div_factors.items():
            factors[number] = max(factors[number], amount)
    return reduce(mul, (n ** a for n, a in factors.items()))

def smallest_multiple(multiple):
    return gen_smallest_divisable(range(1, multiple + 1))

  but I'm curious about why it takes longer to invoke a function which otherwise performs a similar filtering task as a series of conditionals written directly into the list comprehension.

Just take it at face value, calling functions is slow. Also comprehensions do some magic when passed to the AST, which may speed them up. But 6 seconds for the creation of 11650000 stack frames doesn't seem unreasonable to me.

If you wanted to stick with your method, I'd highly recommend you use itertools.count, as then you don't need your recursion. And you won't test a couple thousand numbers after finding your match.

I'd also make a divisors list, to simplify things. Which has a performance cost, due to using any.

import itertools

def smallest_factor(start):
    divisors = range(11, 21)
    options = (i for i in itertools.count(start, 20)
               if not any(i % d for d in divisors))
    return next(options)


Sieve of Eratosthenes using a Javascript array

Since you're just doing steps of 1 and starting with 0, we don't need to take account for those. Your range function can be simplified into the following.

function range(length){
  return Array.apply(null, Array(length)).map(function (_, i) {return i;});
}

Also, a comparison is already a boolean by itself. So your isNotNull could be simplified into the following. We could coerce value into a boolean by using !!, since we're working with numbers, we might encounter 0 which is falsy but technically not null. So we compare explicitly with null instead to avoid this.

function isNotNull(value) {
    return value !== null;
}

You could also inline your search for the next prime into your primes function. You can simply check your number list if the next number has been nulled, and if so, have the loop in primes skip the number.

With that (and hopefully my understanding of the algorithm isn't wrong), here's my take:

function range(length) {
  return Array.apply(null, Array(length)).map(function(_, i) { return i; });
}

function getPrimes(end) {

  // We get the numbers below the square root of the limit. The | 0 is
  // dropping the decimal info, and since range here is zero-indexed,
  // we add 1.
  return range((Math.sqrt(end) | 0) + 1).reduce(function(numbers, root, index) {

    // If the number at root is null, then its multiples may have been
    // nulled by an earlier prime. We bail out. Nothing to do here.
    if (numbers[root] === null) return numbers;

    // We null every multiple, provided it's not 0 and 1
    else if (root !== 0 && root !== 1)
      for (var i = root * root; i < numbers.length; i += root)
        numbers[i] = null;

    // If we reached here, then probably you're looking at 0 or 1
    else numbers[root] = null;

    return numbers;

    // Here's the array that generates 0-to-end. Again, range is
    // zero-indexed so the + 1 is necessary.
  }, range(end + 1)).filter(function(i) {

    // Since 0 and 1 are already nulled, they will fall off here. No
    // additional slicing needed.
    return i !== null;
  });
}

document.write(getPrimes(121).join(','));


Does this SQL code look okay to everyone? I'm new to coding

It is hard to tell without more details. Like @Paparazzi said, it is more clear if you do joins using the join syntax:

SELECT Title
FROM Film F
    INNER JOIN Award A
    ON F.Film = a.FilmID
WHERE
    Award_Category = "Best Documentary"
    AND Award_Ceremony = "Galway Film Fleadh"
    AND F.Year = 2008;

Generally speaking if you are building an app you might want to do your selects using a unique ID column instead. This will be faster because you can create better indexes(ms-sql, mysql) on your tables, plus you can avoid multiple conditionals:

SELECT Title
FROM Film F
    INNER JOIN Award A
    ON F.Film = a.FilmID
WHERE
    F.Film = 1234

This is the same for your delete and presumably your update too, what if you have two directors named Steven Spielberg? Doing data changes based on ID is much more reliable.

For this query it doesn't seem to actually need a join. Is any data being pulled/compared from the Role table? I would look at all your queries to see if they really need the join or not.

SELECT DISTINCT A.Forename, A.Surname
FROM Actor A, Role R
WHERE A.ActorID = R.ActorID
AND Part = "James Bond"

Instead of using LIKE with a wildcard character in the front(thus preventing any index from being used on this field), you might want to look into full text searching if you are using SQL Server.

 SELECT Title
 FROM Film
 WHERE Genre = "Western"
 AND Title LIKE "%Riders%";

The last query with the headline Assuming no actor has the same name. is very confusing, I've never seen a query like that, is that valid sql? I believe group by and having should always be at the end.

If you post your table structure we can probably offer more improvements because from your queries there might be room for normalization improvements as well.

For MySQL run: show create table my_table\G

For SQL Server: right click your table and select Script As then select Create To


Pull back records that include child records

The fact that your ViewModel is almost an identical copy of your entity class is a code smell. ViewModel should represent data as it is to be shown on screen, that means that most properties should be simple types (string, int and bool mostly). Weed them out first, I don't believe you need all the IDs either!

Your repository doesn't do any real projection, so you can get rid of the entire select clause. Use eager loading (Include()) instead of joins (your domain and/or EF config might need to be modified):

var reqMatsInc = (from rm in db.RequiredMaterial.Include(rm => rm.RequiredMaterialRoles)
                  join p in db.Project on rm.ProjectTemplateId equals p.ProjectTemplateId
                  where p.ProjectId == id).

Then, have another method in another class (preferrably in your UI layer) map the result to  your ViewModels.

(may I suggest AutoMapper to handle this task for you, it was made for exactly these kind of things).


Speeding up naive backtracking Sudoku Solver in Haskell

It turns out I made some crucial mistakes: The iteration in solve can stop as soon we have tried all possibilities for one coordinate (x,y) that is not set yet. If we iterate further over (x,y) we get duplicate solutions which makes things blow up, so with following little modification we get results immediately:

isEmpty :: Board -> Coordinates -> Bool
isEmpty b coords = b ! coords == 0

-- check whether board is already full
full :: Board -> Bool
full b = 0 `notElem` [b ! (i,j) | i<-[0..8], j<-[0..8]]

-- recursion to find all solutions to a given board
solve :: Board -> [Board]
solve b
 |full b = [b]
 |otherwise =  concat[ solve $! (insert b (x, y) n)|
                       (x,y) <- take 1 empty,
                       n <- [1..9],
                       possible b (x,y) n]
   where empty = [(x,y) | x<-[0..8],y<-[0..8], isEmpty b (x, y)]

Try it online!


Overall, its nice code.  Easy to read and good use of white space.

I would move the creating of the HashService to a Factory class though.  The way you are using it, I don't think it belongs in the class.

public class HashServiceFactory
{
    public Create(HashAlgorithm algorithm)
    {
        return new HashService(algorithm);
    }
}

// Usage

var factory = new HashServiceFactory();

var sha256Managed = factory.Create(new SHA256Managed());
var md5CryptoServiceProvider = factory.Create(new MD5CryptoServiceProvider());


Shank Transformation to Lebniez series to find Pi recursively


Printing out Pascal's Triangle in row-major format

Like the Fibonacci sequence, calculating Pascal's triangle recursively using a pure functional approach wouldn't be very efficient, since you would repeatedly compute many of the entries.

You've implemented a recursive solution with memoization, which is smarter.  However, with memoization, the solution is stylistically iterative.  Consider the following function, which behaves identically to yours, but is written in a more straightforward manner:

function pascalTriangle(totalLines) {
    var triangle = [];
    while (triangle.length < totalLines) {
        if (triangle.length > 0) {
            var triangleLine = [];
            for (var i = 0; i < triangle.length; i++) {
                if (typeof triangle[triangle.length - 1][i - 1] === 'undefined') {
                    triangleLine.push(1);
                } else {
                    triangleLine.push((triangle[triangle.length - 1][i - 1] + triangle[triangle.length - 1][i]));
                }
            }
            triangleLine.push(1);
            triangle.push(triangleLine);
        } else {
            triangle.push([1]);
        }
    }
    return triangle;
}

You could consider your "recursion" to be a fancy goto.  Alternatively, you could conclude that Pascal's triangle does not lend itself to recursion.

That said, your implementation could be more compact.  Think of deriving the next line this way:

  [ , 1, 3, 3, 1]
+ [1, 3, 3, 1,  ]
—————————————————
  [1, 4, 6, 4, 1]

Then, you can use higher-level thinking: make two arrays with the appropriate offset, and find the sums of the corresponding elements.

function pascalTriangle(totalLines, triangle) {
    // Helper function to add corresponding elements of two arrays
    function sum(a, b) {
        return a.map(function(_, i) {
            return a[i] + b[i];
        });
    };

    if (triangle == null) {                 // Initial call with just one parameter
        triangle = [[1]];
    }
    if (totalLines === triangle.length) {   // Final case
        return triangle;
    }
    var prevLine = triangle[triangle.length - 1];
    var nextLine = sum([0].concat(prevLine), prevLine.concat([0]));
    return arguments.callee(totalLines, triangle.concat([nextLine]));
}

I've used arguments.callee for the function to refer to itself, so that if you rename the function (or make it anonymous), it can still work.


Chunk a large set of characters by a specified set of delimiters and a maximum chunk size

Don't you need to test for delimiters here?  From reading your code I assume we want to max chunk but if inside the chunk there are delimiters we want to break that up.  If the last section fits in the entire chunk it's not checking for delimiters
if (pointer == sourceSpan.Length)
{
    items.Add(sourceSpan.Slice(lazyPointer, pointer - lazyPointer).TrimStart().ToString());
    break;
}

Also you could use IndexOfAny instead of the loop at the end
WARNING this code not tested and just used an example
var slice = sourceSpan.Slice(lazyPointer, pointer - lazyPointer);
var contains = slice.IndexOfAny(delimeters);
while (contains > -1)
{
    items.Add(slice.Slice(0, contains + 1).ToString());
    slice = slice.Slice(contains + 1);
    contains = slice.IndexOfAny(delimeters);
}

Now some other points that I think you should split by delimiters first then chunks.  Instead of chunks then delimiters.  If I have a string of  "12345.6789.8.654321" and split by 7.   The first two coming out would be "12345" <-- looks good but then the next chunk would be "6" then chunk after that would be "789","8","6","54321"  if we split by delimiters first then chunked them it would output what I think most people would expect.


Short and clean using null-coalescing operator:

public async Task<WebData> GetDataByIdAsync(GetDataById input)
{
    return await DataAccess.FindDataById<TwitterData>(input.Id)??
           await DataAccess.FindDataById<FacebookData>(input.Id)??
           await DataAccess.FindDataById<LinkedinData>(input.Id);
}


First off, "cross platform capability for ANSI color printing" doesn't quite make sense (if I understand correctly). ANSI color printing is only going to work on terminals that are ANSI compatible.

Therefore, it doesn't really matter what OS it is: if it's an ANSI terminal, you can use ANSI colored output.

Therefore, you can remove the checking of the operating system.

Note: according to this answer,

  "All modern terminal emulators use ANSI escape codes to show colours
  and other things."

Judging by the name of the method your presented and the context of the code, you have created a separate method for each color.

This sounds like you are repeating yourself a lot.
It's not very flexible for the code that is using your library.

I recommend that you create a single method print_color_string that takes a string and the color to print.

def print_color_string(str, color):
    ansi_color = getattr(Fore, color)
    if ansi_color:
        sys.stdout.write(ansi_color + p_str + Fore.RESET)
    else:
        # throw error because color is not a valid color


I would change

public int getDecimal(char character)
{
    for (int i = 0; i <= 255; i++)
    {
         if (character == (char) i)
         {
              return i;
          }
     }
     return -1;
}

To just

public int getDecimal(char character)
{
     if(character<0||character>255)
          return -1;
     return character;
}

, As char is a number, too.

Also try using >> operator to get nth binary digit, which means division by 2.

number = (int) (number / 2);

To

number = number >>1;

I don't know if it would be faster in java, but it  works faster in old computer's assembly program(Division was expensive than just shifting)

If you use assembly you can access carry flags and optimize it.

For more information about it, refer here.

Provided that al holds the target number and bx holds the target string address, and cx holds 8,

L1:                  ; This is the loop
mov dl, '0'      ; Ascii character zero
shl al, 1          ; Upper bit now in carry flag
adc dl, 0        ; Adds carry flag - 0 or 1
mov [bx], dl   ; Save digit to current position
inc bx             ; Next position
loop L1          ; Counts down cx
mov [bx], 0    ; Zero terminate (might need to use register)


You have unicode strings as comments. Just use comments.
You rely on manipulating global state, not a good idea. Instead,
have function return things. You don't use any return statements
anywhere in your code.
You use not a == b instead of a != b in several places
You use a in xrange(b,c) where b <= a < c would be better
All of your for loops use xrange, usually you want to iterate over the container directly
Your yearCheck function doesn't do anything. The if condition is impossible to satisfy. It looks like you discovered this, because you've implemented the logic down in the printer function.
You delay converting the data components to integer, this only serves to complexicate your code.
You generate a list of leap years, but you only ever check the years 0, 1, 2 and 3.
You keep the data inside the list the whole time. Code is easier to follow if you don't do that. Pull the data out of lists into local variables rather then indexing into the list.

Here is a reworking of your approach:

NORMAL_MONTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
LEAP_MONTHS = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def get_month_lengths(year):
    """
    Returns appropriate months for a particular year
    """
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return LEAP_MONTHS
        else:
            return LEAP_MONTHS
    return NORMAL_MONTHS

def print_date(year, month, day):
    """
    Print the given date
    """
    if year < 2000:
        year += 2000
    print u'%04d-%02d-%02d' % (year, month, day)

# Looks for legal dates, first [Y<M<D] then [M<Y<D] then [M,D,Y]

def dateMaker(data):
    """
    Try different ways of interpretating the date
    """
    a, b, c = data

    for year, month, day in [(c,b,a), (c,a,a), (b,a,c)]:
        month_lengths = get_month_lengths(year)
        if month <= 12 and day <= month_lengths[month - 1]:
            print_date(year, month, day)
            return

    print unicode(data) + u" is illegal"

data = sorted(map(int, raw_input().split(u"/")))
dateMaker(data)


PHP snippet to create image gallery from folders with jpgs

Is PHP_EOL the best way to add a newline character in order to make the output HTML look better?

No, I don't think so. If you want your HTML nice on output, why not have it nice in the source code as well?

So instead of this:

echo "
".PHP_EOL."
".basename($file, ".jpg")."
".PHP_EOL."    ".PHP_EOL."
".PHP_EOL;

have this:

echo "

".basename($file, ".jpg")."

;

  Have I used any deprecated functions?

I don't think so. But generally, you can see that yourself, when you enable warnings in development (don't forget to turn them of in production though).

  Would you please offer any tips regarding best practices, or how to make my code look more readable?

You could extract code blocks to functions
You could use more whitespace (eg around .)
You could extract duplicate function calls to well-named variables
have constants such as fixed directory names in as few places as possibly, to make changing it easier

This would give you something like this. It's not perfect, but hopefully a good start:

echo formatHTMLforDirectory('images/otros/');

/**
TODO PHPDoc comment
*/
function formatHTMLforDirectory($basedirectory) {
    $directories = glob("$basedirectory/*", GLOB_ONLYDIR);
    $html = "";
    foreach($directories as $directory) {
        $directoryName = basename($directory);
        $html .= "

$directoryName

                    ";
        $files = glob("$basedirectory/$directoryName/*.{jpg}", GLOB_BRACE);
        $html .= formatHTMLforFiles($files);
        $html .= "
";
    }
    return $hmtl;
}

/**
TODO PHPDoc comment
*/
function formatHTMLforFiles(array $files) {
    $html = "";
    foreach($files as $file) {
        $filename = basename($file, ".jpg");
            $html .+ "

$filename

";
    }
    return $hmtl;
}

Misc

I always get nervous when data from the outside is echoed unencoded, as it can lead to XSS. If you allow users to upload image files, you are already vulnerable. But even if not, you may allow this in the future, which would make you vulnerable then.
You might want to think about using a templating engine such as twig. Mixing HTML and PHP often leads to hard to read code.


Hide and un-hide rows then sort on Worksheet_Activate event

There are two things that I think can easily be done.

Find out where the data actually ends rather than always using row 500. Use a function like this:

Function LastRowNum(sheetName As String, columnLetter As String) As Long

    With ThisWorkbook.Worksheets(sheetName)
        LastRowNum = .Range(columnLetter & .Rows.Count).End(xlUp).Row
    End With

End Function

If you are going to use an AutoFilter in the SortingRisk proc then why not use it to hide the empty rows? It should be much quicker than looping through cells using VBA.


method isInteger(BigDecimal number) isn't compliant with sonar rules

You should ignore the warning. However this warning is not unfounded as exceptions are costly (stack unwinding) and in this case the exception might even happen in maybe 90% of the cases.

So in this case preferably an alternative should be sought:

public boolean isInteger(BigDecimal number) {
    return number.stripTrailingZeros().scale() <= 0;
}

Here stringTrailingZeros would turn 600.00 into 6E2, hence with scale -2, and 0.0600 would become 6E-2 with scale 2.

Less code, hence even Wally points on the Dilbert scale.

P.S. there exist SuppressWarning annotations for SonarLint, though neat programmer that I am, I do not know the warning key.


What parts of my Python code are adopting a poor style and why?

I also have a tendency to do things like spam = fun() because I do not
  know how to correctly make Python call a function which changes a
  variable in the scope of where the function was called.

You can't. You cannot replace a variable in an outer scope. So in your case, you cannot replace the list with a new list, although you can modify the list. To make it clear

variable = expression

replaces a variable, whereas pretty much anything else:

variable[:] = expression
variable.append(expression)
del variable[:]

Modifies the object. The bottom three will take effect across all references to the object. Whereas the one before replaces the object with another one and won't affect any other references.

Stylistically, it somestimes makes sense to have a function modify a list, and other times it makes sense for a function to return a whole new list. What makes sense depends on the situation. The one rule I'd pretty much always try to follow is to not do both.

def randomize_list(the_list, x=MAX):
    for i in range(len(the_list)):
        the_list[i] = random.randint(1, x)

This isn't a good place to use a modified list. The incoming list is ignored except for the length. It'd be more useful as a function that returns a a new list given a size something like:

def random_list(length, maximum = MAX):
    random_list = []
    for _ in range(length):
        random_list.append( random.randint(1, maximum) )
    return random_list

def lengthen_list(the_list, desired_length, x=MAX):
    if len(the_list) >= desired_length:
        print "erroneous call to lengthen_list(), desired_length is too small"

Don't report errors by print, raise an exception

 raise Exception("erroneous call...")

        return the_list
    while(len(the_list) < desired_length):
        the_list.append(random.randint(1, x))
        # organize the_set
        the_list = set(the_list)
        the_list = list(the_list)

That's not an efficient way to do that. You constantly convert back between a list and set. Instead do something like

 new_value = random.randint(1, maximum)
 if new_value not in the_list:
      the_list.append(new_value)

That way you avoid the jumping back and forth, and it also modifies the original object rather then creating a new list.

    return the_list

This particular function could go either way in terms of modifying or returning the list. Its a judgement call which way to go.

  Also is it bad to be writing code in this space and I should create a
  function or class to call from that space which contains most my code?

Yes, you should really put everything in a function and not at the main level for all but the most trivial scripts.