Merging some of the suggestions you've received so far this is what I think it should look like (I removed the comments for this review):

internal class AppleConfig
{
    private Dictionary<string, string> _configItems = new Dictionary<string, string>();

    private readonly string _fileName;

    private readonly ILog _log = LogManager.GetLogger(typeof(AppleConfig));

    public AppleConfig(string fileName)
    {
        _fileName = fileName;

        // first time we want it to work
        if(!LoadConfig())
        {
            throw new Exception("Initalization failed.");
        }
    }

    public string this[string key]
    {
        // this might throw an exception if key not found
        get { return _configItems[key]; }
    }

    public bool IsInitialized
    {
        get { return _configItems != null; }
    }

    public bool LoadConfig()
    {
        try
        {
            _configItems =
                File.ReadLines(_fileName)
                    .Where(IsConfigurationLine)
                    .Select(line => line.Split('='))
                    .ToDictionary(line => line[0], line => line[1]);

            return true;
        }
        catch (Exception exception)
        {
            _log.Error(exception); // assuming overload that takes an exception.
            return false;
        }
    }

    private bool IsConfigurationLine(string line)
    {
        return !line.StartsWith("#") && line.Contains("=");
    }
}

You don't need the _isInitialized field, you can check the dictionary if it's not null
You don't need the big loop but just a short linq query (by @Konrad Morawski)
You don't need the Initialize method and all the crazy logic ;-) but a simple LoadConfig method that you call in the constructor and later if you want to load it again
You don't need the FileInfo class but just a simple string for the path
There's still a lot that might be improved but it all depends how you are going to use it and whether you need all the improvements at all: will someone else use it? Do you need/want meaningful exceptions (I think it's always hard to implement them if you want them to make it possible to find an error right away).
After all I think the IsInitialized property is also not necessary, it doesn't have any usage. The object cannot actually be in an un-initialized state beacause it would be useless then so I would say it can be removed without losing anything. The load method either worked and everything is fine or it didn't and the constuructor throws an exception.


Overall, this looks pretty good. If it were me, I'd use a more descriptive name for the top of the stack such as topOfStack or just top. tos doesn't really mean anything, so without a comment describing it, I would be confused seeing that in code. (And if you need to write a comment to explain a variable name, you've probably named it incorrectly.)

I'm not sure your set() method works correctly. From the description it sounds like it shouldn't take any arguments and should set tos to 0. But it's possible I misunderstood. If you set the top to some passed-in value, then you have a bunch of junk on the stack between its previous value and the current value, which probably isn't what you want.


if (invertedAppearance()) {
        this->setValue( maximum() - newVal );
} else {
        this->setValue(newVal);
}

You should not be posting if/else statements without Curly Braces. The style leaves you open for massive bugs, and as an after thought: makes it cumbersome for you or other developers to add to this code.

So for example, let's say you are editing or debugging your code, and decide to comment out a line:

if (invertedAppearance())
    this->setValue( maximum() - newVal );
else
    // this->setValue(newVal);

event->accept();

Do you see the issue?


Chaining asynchronous tasks that must run sequentially

I would use lock instead of Interlocked, because its much easier to follow and debug. Unless you are after some kind of micro optimization, I think you should keep it simple:

lock (lock)
{
    if (lastTask == null)
    {
       task.Start(scheduler);
    }
    else
    {
        lastTask.ContinueWith(...);
    }
    lastTask = task;
}

I think you can modify your lambda expression to get a current task:

Task task = null;
task = new Task ((action) =>
     {
         CurrentTask = task;
         ((Action<T>)action) (wrappedValue);
     }, operation);

Though I am not too experienced with TPL, so there might be an easier way.


Don't use wildcard imports.

Import tkinter with import tkinter as tk, and then prefix all of your calls to tkinter classes with tk.. For example:

import tkinter as tk

window = tk.Tk()
...
title = tk.Label(window, text="Basic Converter", font="Calibri 16")
filemenu = tk.Menu(window)

...

PEP8 is a set of guidelines that most python programmers follow, and it recommends against wildcard imports.

Don't call grid or pack inline

In python, x().y() always returns the value of y(). In tkinter, grid, pac, and place all return None. Thus, when you do this:

arrow = Label(window, text="--->", font="Calibri 20").grid(row=1, column=1)

... all you're doing is setting arrow to None, which renders arrow useless. Plus, doing it inline (or worse, sometimes in line and sometimes now) makes the code hard to read.

Which leads us to the next point...

Separate layout from widget creation.

I see this mistake all the time: create a widget, call grid, create a widget, call grid, ... This results in code that is hard to read, and makes it hard to visualize the layout. If you have to change the layout, such as changing the order of two rows, it's easier if those two rows are together in the code rather than intermixed with other code.

As a rule of thumb, create all widgets within a given group together, and lay them out together.

For example:

title = Label(window, text="Basic Converter", font="Calibri 16")
inputEntry = Entry(window)
arrow = Label(window, text="--->", font="Calibri 20")
convertButton = Button(window, text='Convert!', command=converter)
outputEntry = Entry(window, textvariable=result)
scrollbar = Scrollbar(window)   #left scrollbar
...
title.grid(columnspan=3)
inputEntry.grid(row=1, column=0)
arrow.grid(row=1, column=1)
convertButton..grid(row=2, column=1)
outputEntry.grid(row=1, column=2)
scrollbar.grid(row=2, column=0, sticky = NE + SE)
...

In this specific example everything is in the root window so it doesn't matter quite so much, but if you used multiple frames for organizing your widgets this would make it much easier to see which widgets were grouped together.

Make your UI responsive

When I resized your window, the layout didn't respond very well. This is what I see when I resize the program; notice how the scrollbars are the wrong size, the listboxes didn't expand, etc.

Tkinter makes this easy to do, but you have to use the options tkinter gives you. Think about what should happen when the user resizes the program. This becomes much easier when you group all of your calls to grid together.


Extracting the first two initials of a person's name

I think you should be able to get rid of the replace() by testing the position of the token in an additional predicate.

You should also be able to remove the string-join() (unless you don't want spaces between the initials).

You can also remove the string-length() test by adjusting the regex for -.

New function based on above suggestions:

<xsl:function name="pull_it:get_initials">
  <xsl:param name="names"/>
  <xsl:value-of select="
    for $token in tokenize($names,'(-+|\s+)')[2 >= position()]
    return concat(substring($token,1,1),'.')
    "/>
</xsl:function>

Complete example (used Saxon-HE 9.5 to test)...

XML Input (Added test VI)

<doc>
    <name>
        <surname>Test I</surname>
        <given-names>Chris</given-names>
    </name>
    <name>
        <surname>Test II</surname>
        <given-names>Chris Chris</given-names>
    </name>
    <name>
        <surname>Test III</surname>
        <given-names>Chris Eat Meat</given-names>
    </name>
    <name>
        <surname>Test IV</surname>
        <given-names>Chris-Eat Meat</given-names>
    </name>
    <name>
        <surname>Test V</surname>
        <given-names>Chris-Eat-Meat</given-names>
    </name>
    <name>
        <surname>Test VI</surname>
        <given-names>Chris---Eat----Meat</given-names>
    </name>
</doc>

XSLT 2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:pull_it="pull_it"
  exclude-result-prefixes="pull_it">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:function name="pull_it:get_initials">
    <xsl:param name="names"/>
    <xsl:value-of select="
      for $token in tokenize($names,'(-+|\s+)')[2 >= position()]
      return concat(substring($token,1,1),'.')
      "/>
  </xsl:function>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="name">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <initials><xsl:value-of select="pull_it:get_initials(given-names)"/></initials>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

XML Output

<doc>
   <name>
      <surname>Test I</surname>
      <given-names>Chris</given-names>
      <initials>C.</initials>
   </name>
   <name>
      <surname>Test II</surname>
      <given-names>Chris Chris</given-names>
      <initials>C. C.</initials>
   </name>
   <name>
      <surname>Test III</surname>
      <given-names>Chris Eat Meat</given-names>
      <initials>C. E.</initials>
   </name>
   <name>
      <surname>Test IV</surname>
      <given-names>Chris-Eat Meat</given-names>
      <initials>C. E.</initials>
   </name>
   <name>
      <surname>Test V</surname>
      <given-names>Chris-Eat-Meat</given-names>
      <initials>C. E.</initials>
   </name>
   <name>
      <surname>Test V</surname>
      <given-names>Chris---Eat----Meat</given-names>
      <initials>C. E.</initials>
   </name>
</doc>


Calculation in Concern module using Rails

Since you're mixing methods into ActiveRecord::Base, you might as well extend it proper:

class ActiveRecord::Base
  def self.paged(...)
    ...
  end
end

No concerns necessary; you're just extending a class. Put it into a file in config/initializers and it'll load when the app spins up.

About what you're mixing in:

default_per_page doesn't make sense as a mixin. It's not the responsibility of every ActiveRecord-derived class to have a shortcut for fetching a global config value. The methods you add to a class via mixins should make as much sense, as if you'd added them directly to just that class.
I'd place shortcuts like that in e.g. a separate helper module, and call it there.
Use Rails.configuration instead of <YourAppName>.config if you're aiming for reusable code.
Consider using hashes for method parameters. It makes calling your methods simpler and more descriptive.
Be consistent with your parentheses. You declaration of normalize_per_page omits the parentheses, but your declaration of normalize_page includes them. Personally, I always use parens in method declarations.
Do not access params in a model. Keep that in the controller, and only the controller; it's its job. This also means keeping the normalize_page  method (which I'd call constrain_page_number, because it doesn't normalize a page, but constrains a number) in the controller. You can simply add it to ApplicationController to have available:

# in app/application_controller.rb

protected

def constrain_page_number(number, record_count, per_page = nil)
  per_page ||= PagniationHelpers.default_per_page # our helper module
  [1, number, (record_count / per_page).floor + 1].sort[1]
end

However, in my view, your controller should send a redirect if the page number in out of bounds - don't just rewrite it behind the scenes. So you might want something like this instead:

def valid_page_number?(number, record_count, per_page = nil)
  per_page ||= PagniationHelpers.default_per_page # our helper module
  max = (record_count / per_page).floor + 1
  (1..max).cover?(number)
end

Now, something that'd might make more sense to include in every model would be a max_page method. It'd allow you to more easily check the page number in the controller.
Of course, such a method would (unlike the above) have to rely on just the default scope when counting the number of records. Still, it might be useful.

In all I end with something like this (plus the controller method above):

module PagniationHelpers
  module_function

  def default_per_page
    Rails.config.custom.default_per_page_pagination
  end
end

class ActiveRecord::Base
  class << self
    def paged(page, per_page = nil)
      per_page ||= PagniationHelpers.default_per_page
      self.paginate(page: page, per_page: per_page)
    end
  end
end

Buuuut of course, it looks like you're using the will_paginate gem. In that case, forget the code above. Instead, do this in an initializer file somewhere:

WillPaginate.per_page = 10 # or whatever default you want

and in ApplicationController do:

def max_page_number(record_count, per_page = nil)
  per_page ||= WillPaginate.per_page
  (record_count / per_page).floor + 1
end

def valid_page_number?(number, record_count, per_page = nil)
  max = max_page_number(record_count, per_page)
  (1..max).cover?(number)
end

def constrain_page_number(number, record_count, per_page = nil)
  max = max_page_number(record_count, per_page)
  [1, number, max].sort[1]
end

And in your controller actions you can do something like

def index
  page = params[:page].try(:to_i) || 1
  unless valid_page_number?(page, Post.count)
    redirect_to posts_path(page: constrain_page_number(page, Post.count))
  end
  @posts = Post.paginate(:page => page)
  #...
end


Script to unpack archives of various kinds

I'm not sure why we have #!/bin/bash - it looks like plain, portable #!/bin/sh would be fine here.
Things I immediately like include the good error handling, using &2 for error messages and exiting non-zero.
All the tar commands can be combined, as tar is able (with -a) to automatically identify any compression scheme it handles.
As there's no need to continue once the archiver is run, we can replace the shell process using exec.  E.g.
case $1 in
    *.7z) exec 7z e "$1"
        ;;

Don't do that if we extend the program to process multiple input files, though (see below).
If we take the usual convention of flags first, then it makes it easier when we decide we want to handle more options (e.g. -v, so we can default to quiet operation).  And we can combine the two big case constructs by always passing a directory, but defaulting to the current working directory:
destination=.

die() {
    printf '%s\n' "$@" >&2
    exit 1
}

do_extract() {
    case $1 in
        *.tar.*|*.t[bg]z) tar xaf "$1" -C "$destination"
            ;;
        *.jar|*.zip) unzip "$1" -d "$destination"
            ;;
        # ...
    esac
}

while [ $# -ge 1 ]
do
    case "$1" in
        -d)
            [ $# -gt 1 ] || die "Usage: $0 [-d directory] file..."
            destination=$2
            shift 2
            ;;
        -*)
            die "Unrecognised option: $1"
        *)
            do_extract "$1"
            shift
    esac
done

Be careful with echo:

usage() {
    echo "Usage: nzip [FILE]..."
    echo "By default file(s) will be extracted to the working directory."
    echo
    echo "OPTIONS.."
    echo
    echo "-d, --directory, eg. nzip [file] [-d] [directory]"
    echo
    echo
}

Other (e.g. future) versions of echo may treat that -d as indicating a flag.
I'd be inclined to use a here-file for this:
usage() {
    cat <<'END'
Usage: nzip [FILE] [-d DESTINATION]
By default file(s) will be extracted to the working directory.

OPTIONS:
    -d destination
END
}

Note that I've changed the usage line, because we support only one file, and -d and the destination argument go together (and it's misleading to call it "directory" when it may be a non-directory name if we're unpacking a single file).


I noticed you defined full read/write accessors on all the slots on your message queue class, yet you bypass all of that and just use with-slots. Are you planning on exporting those accessors as part of the API? It seems like you wouldn't want to encourage people to monkey with those slot values, so probably not. You could also drop :initarg from everything but max-len.


Implementation of the Jacobi Symbol in C

I am only looking for some feedback on my coding style.

Formatting is good. I hope it is auto formatted.

Respect the presentation width

Rather than oblige a horizontal scroll bar, auto format to a narrower width to avoid that.

Avoid dogma

"to ONLY USE ONE return statement in functions and NOT to use things like break, continue or go-to." --> This is a reasonable goal, but better to code for clarity.  Use break, continue and even sometimes goto when it provides cleaner code.

  How could I improve?

Use short to save space in arrays - not here

short jacobi(long a, long n) returns 0,1,-1.  There is no space, code, performance savings expected with short.  Recommend returning int here. int is often the optimal type for an integer.

// short result = 1;
int result = 1;
...
return result;

Cryptography begs for unsigned types

Instead of long, consider the widest unsigned type of uintmax_t or the widest fixed size type: uint64_t.

Unsigned types will improve code performance.

long n ... n_mod8 = n % 8; requires a division as n % 8 has 15 different results [-7 ... 7].  With unsigned long n, n % 8 is simply a mask operation.

Consider bool

For clarity, use bool.

//short condition = 1;
//while (condition == 1) {
bool condition = true;
while (condition) {

Remove debug code

e.g. // printf("(%d|%d) and result = %d \n", a, n, result);.

Error messages: consider stderr

// printf("Wrong input for the Jacobi Symbol:...
fprintf(stderr, "Wrong input for the Jacobi Symbol: ...

Post expected test code results

What should printf("%d", jacobi(4852777,12408107)); print?

Consider a few more test cases.

Post compilable code

Trailing ``` breaks compilation.

Minor

// The The if-condition below utilises the fact that (0|n) = 0.
to
// The if-condition below utilises the fact that (0|n) = 0.

  Is anything unclearly formulated?

I'd add a reference for Jacobi symbol.

// https://en.wikipedia.org/wiki/Jacobi_symbol

n == 1?

Hmmm. Jacobi symbol allows n==1.  Code here does not.


How to decrease memory usage in codeeval Road Trip challenge

I don't think it's a good idea to preprocess the line so much.  line = line.strip() duplicates the line, for no benefit.  I don't know why if line == "": continue should be needed.  line = line.replace(';', ' ').replace(',', ' ').split() degrades the data, and takes two passes to do it.

Here's how I would read the input:

for line in fileinput.input():
    route = itertools.chain([0], sorted(
        int(city.group(1)) for city in re.finditer(r'[A-Za-z]+,(\d+);', line)
    ))

Using fileinput.input() will let you take input from either a file specified on the command line, or sys.stdin if no file is specified.  re.finditer() will look for the pattern and capture the numbers that you need.

In Python 2, you should use xrange() instead of range().  However, if you capture just the numbers, as I've done above, then you wouldn't need to use range() or xrange() to extract every other item.

Each of your list comprehensions results in another temporary copy of the data.  result.insert(0, distances[0]) is also bad for performance, since every entry must be copied to make room for one entry at the front of the list.

To finish off the solution, I would do this:

print(','.join(str(b - a) for a, b in pairwise(route)))

… using the pairwise() recipe from itertools.


Refactor .each where each is redirected into a hash

I think this is where you are trying to get to:

class Busy
  def event_info
    {
      :id => id,
      :title => title,
      :start => busy_start_time(start_date, start_time),
      :end => busy_end_time(end_date, end_time),
      :allDay => false,
      :recurring => false,
      :color => 'black',
    }
  end
end

@events = @busy_items.map(&:event_info)

Some additional notes:

There is no need to initialize @events to an empty array, favor expressions over statements with side-effects (map, select, reduce and so on, instead of each).
I renamed the variable to busy_items to emphasize it's a collection.
Busy does not sound right for a class name. Classes are usually nouns, not adjectives. What's the nature of this class?


Exception handling for a chain of prompts

The whole port and count thing is a total waste of time. If you were stuck with it:

port is redundant, as break is what actually ends the loop;
If port was being used (e.g. while port:) it should be a bool (True/False) rather than an int (1/0);
You shouldn't have whitespace around the = for default argument values (def inputin(count=1, port=0):);
The if conditions should have more space and fewer parentheses: if port == 0 and count == 3:; and
count+=-1 should be count -= 1.

Only two of your inputs actually need to be numbers, yet you wrap the whole thing in try; that block should be as short as you can make it. You can factor out the integer inputs for much cleaner code (see e.g. Asking the user for input until they give a valid response). For the other three inputs the return from input is always a string, so the str calls are totally redundant.

Compare:

def int_input(prompt):
    """Validate integer-only user input."""
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter an integer.")

def input_in():
    """Get required user inputs."""
    background = input("Enter the background color: ")
    num_sides = int_input("Enter the number of sides: ")
    arm_len = int_input("Enter the length of each side: ")
    turtle_color = input("Enter the turtle color: ")
    turtle_shape = input("Enter the turtle shape: ")
    ...

Note the adherence to the style guide and use of docstrings to explain what each function does.

As additional exercises:

Add limits to the integer validation, allowing a minimum and maximum to be set for the function (a negative arm_len wouldn't make much sense, for example);
Create a color_input function to validate the user's color selection, and use it where appropriate; and
Create a shape_input function to do the same for shapes.


Activate submit button on form change and detach event listener

If you use event.currentTarget instead of form, you can declare the event handler function once and reuse it:

function formHandlerChange(event) {
    const form = event.currentTarget;
    const submit = form.querySelector('.disabled');
    submit.classList.remove('disabled');
    form.removeEventListener('change', formHandlerChange);
}

for (const form of document.querySelectorAll('form')) {
    form.addEventListener('change', formHandlerChange);
}

(Note: I also used querySelector() and querySelectorAll() as they are more flexible than the various getElementBy methods)


Get the last activity per user per day in a dataframe

Instead of using tail, if you only need one item there are the first and last methods, which do exactly what you think they would do with grouped dataframes:
df_example.groupby(['id', 'date']).last()

I doubt there is a faster way to create the activity column. And you have to create a new one because of your requirement with what counts to which day.
But you can speed up getting the date. Using apply with a lambda is about the second slowest way to work with pandas (manual Python for loops are slower). Instead use the vectorized datetime functions:
df_example['date'] = df_example['activity'].dt.date

Potential bug:
Note that df_example.sort_values(by=['id', 'activity']) returns the sorted dataframe, it does not modify it inplace. Either assign it back to df_example, or use inplace=True.
The same is true for groupby, you probably want to assign the result to a variable as well in order to do something else with it afterwards.

Python has an official style-guide, PEP8. While it recommends using spaces around the = operator when using it for assignment, it recommends using no spaces when using it for keyword arguments.


Generic LinkedList with add/exists/delete/dlear/iteration functionality

I would implement ICollection<T> in addition to IEnumerable<T>. It should be easy and straightforward.
Public setters of the Head and Tail properties will allow users of your class to corrupt the structure of linked list.
Not sure if you need to expose Head and Tail as properties at all, as they are the only ones who expose the SinglyLinkedListNode<T> instances used internally.
AddToEnd implementation can be simplified. The case of Head == Tail doesn't differ from else clause. So the method can be refactored as following (note that the non-null Head implies non-null Tail, this should be guaranteed by the design of your class):

public void AddToEnd(T value)
{
    var newNode = new SinglyLinkedListNode<T>
    {
        Value = value,
        Next = null
    };

    if (Head == null)
    {
        Head = newNode;
    }
    else
    {
        Tail.Next = newNode;
    }

    Tail = newNode;
}

Similar refactorings can be applied to AddToBeginning. When you create a new node to be inserted at the beginning, its Next property will always refer to original Head node, whether it was null (list is empty) or actual node. Thus the method can be reduced to:

public void AddToBeginning(T value)
{
    Head = new SinglyLinkedListNode<T>
    {
        Value = value,
        Next = Head
    };

    if (Tail == null)
    {
        Tail = Head;
    }
}

Delete method has a bug - it will never assign null to Tail, even if all elements are deleted from the list.


Current code
Before discussing the algorithm I want to discuss the current code.
The code currently uses functional approaches - like forEach() methods. This is great for readability but because a function is called for every iteration of each loop, performance can be worse than a regular for loop - e.g.  each function adds to the call stack.
The current code also uses hasOwnProperty. For a plain object the in operator could be used since it doesn't matter if the property would be inherited or not.
The last block is this:

const finalErr = []

Object.keys(triplet_memory).forEach(el => {
    const elements = el.split('/').map((element) => {
        return parseInt(element)
    })
    finalErr.push(elements)
})
return finalErr

It is interesting that there is a .map() call nested inside a .forEach() loop that pushes elements into an array - the latter is the essence of a .map() call. So the .forEach() could be simplified to a .map() call:
return Object.keys(triplet_memory).map(el => {
    return el.split('/').map((element) => {
        return parseInt(element)
    })
})

This way there is no need to manually create finalErr, push elements into it and then return it at the end.
Different Algorithm
There are multiple posts about this problem on code review (and SO as well). This buzzfeed article explains multiple approaches including The hash map solution and the two pointer trick, the latter of those two is a great solution.

Two pointer trick
The ‘two pointer trick’ gives a really nice solution to 3sum that doesn’t require any extra data structures. It runs really quickly and some interviewers ‘expect’ this solution (which might be somewhat unfair, but now that you’re seeing it, it’s to your advantage).
For the two pointer solution, the array must first be sorted, then we can use the sorted structure to cut down the number of comparisons we do. The idea is shown in this picture:

vector<vector<int>> threeSum(vector<int>& nums) {
 vector<vector<int>> output;
 sort(nums.begin(), nums.end());
 for (int i = 0; i < nums.size(); ++i) {
   // Never let i refer to the same value twice to avoid duplicates.
   if (i != 0 && nums[i] == nums[i - 1]) continue;
   int j = i + 1;
   int k = nums.size() - 1;
   while (j < k) {
     if (nums[i] + nums[j] + nums[k] == 0) {
       output.push_back({nums[i], nums[j], nums[k]});
       ++j;
       // Never let j refer to the same value twice (in an output) to avoid duplicates
       while (j < k && nums[j] == nums[j-1]) ++j;
     } else if (nums[i] + nums[j] + nums[k] < 0) {
       ++j;
     } else {
       --k;
     }
   }
 }
 return output;

1


There's really only rather small things I'd change / adapt

CREATE OR REPLACE FUNCTION normalize_moderation_log_overflow() RETURNS INTEGER AS

Since you always return 1, this function actually should be a void.

CREATE OR REPLACE FUNCTION normalize_moderation_log_oveflow () RETURNS VOID AS

Your Indentation seems off a little:

BEGIN
    FOR logs ...
  FROM ...

I'd prefer to indent the SELECT statement in reference to the FOR .. LOOP like this:

BEGIN
  FOR logs IN SELECT ...
      FROM errors

AND error_type_id = (SELECT id FROM error_types WHERE normalizer_type = 'moderation_log_overflow')

This can (and probably should be) extracted into a constant

log_overflow CONSTANT INT := SELECT id FROM error_types WHERE normalizer_type = 'moderation_log_overflow' LIMIT 1;

Which makes the condition look like this:

AND error_type_id = log_overflow

    UPDATE errors
    SET state = #{ Error.states[:resolved] };

All other DML statements you have are in a single line, why not this one, too?

UPDATE errors SET state = #{ Error.states[:resolved] };


Is there any way in which this code can be improved?

The procedure parameters should reflect the underlying data types. Each component of an identifier is sysname, a synonym for nvarchar(128) NOT NULL. Using varchar(50) artificially limits the length, and characters that might be used. Likewise, Unicode should be used for the dynamic SQL itself.
The user-supplied table identifier strings should be split using PARSENAME into schema and object portions, then quoted using QUOTENAME. This is safer and more correct than manually surrounding the whole identifier with square brackets.
QUOTENAME returns nvarchar(258), so a safe type for the input is twice this, plus one for the . separator, giving nvarchar(517).
Add a @Debug bit parameter, or similar, so the user can view the generated dynamic SQL (and the associated execution plan) before deciding to execute it.
The procedure should have a basic error handling framework, for example as described by Erland Sommarskog in Error and Transaction Handling in SQL Server.
Add some basic checks for things like object existence, the presence of a primary key, and so on.
STRING_AGG should normally have a WITHIN GROUP clause to provide deterministic ordering.
Compute the distinct column lists once, then reuse this value as necessary.
Separate the code into more steps to make it clearer, and easier to debug. Try to avoid code that scrolls off to the right, and deeply nested function calls.
It is difficult to anticipate all the conditions that could cause the MERGE statement to fail, but consider adding extra checks for e.g. computed columns. Even if this is covered by another condition, being explicit makes the intent clearer.
Avoid hard-coding a numeric type id. Use the TYPE_ID function instead.
Using CONCAT_WS can result in cleaner code than CONCAT when using separators.

Also, I am not sure how to make this work with compound keys...

This can be done by consulting sys.key_constraints and sys.index_columns, see the example code below.
Example
This illustrates how the above points might be incorporated:
CREATE OR ALTER PROCEDURE dbo.MergeTables
    @Source nvarchar(517),
    @Target nvarchar(517),
    @Debug bit = 0
AS
BEGIN
    SET NOCOUNT, XACT_ABORT ON;
    BEGIN TRY
        -- Cannot specify a database or server in the input table names
        IF PARSENAME(@Source, 3) IS NOT NULL
        BEGIN
            RAISERROR(N'Three- or four-part names are not supported for the table identifer %s.', 16, 1, @Source);
        END;

        IF PARSENAME(@Target, 3) IS NOT NULL
        BEGIN
            RAISERROR(N'Three- or four-part names are not supported for the table identifer %s.', 16, 1, @Target);
        END;

        -- Break and quote input e.g. 'My Schema.My Object' - > [My Schema].[My Object]
        SET @Source = CONCAT_WS(N'.',
            QUOTENAME(PARSENAME(@Source, 2)),
            QUOTENAME(PARSENAME(@Source, 1)));

        SET @Target = CONCAT_WS(N'.',
            QUOTENAME(PARSENAME(@Target, 2)),
            QUOTENAME(PARSENAME(@Target, 1)));

        -- Check tables are accessible
        DECLARE @SourceID integer = OBJECT_ID(@Source, N'U');
        DECLARE @TargetID integer = OBJECT_ID(@Target, N'U');

        IF @SourceID IS NULL
        BEGIN
            RAISERROR(N'Table %s not found in the current database.', 16, 1, @Source);
        END;

        IF @TargetID IS NULL
        BEGIN
            RAISERROR(N'Table %s not found in the current database.', 16, 1, @Target);
        END;

        IF CONVERT(integer, OBJECTPROPERTYEX(@SourceID, 'TableHasPrimaryKey')) = 0
        BEGIN
            RAISERROR(N'Table %s does not have a primary key.', 16, 1, @Source);
        END;

        IF CONVERT(integer, OBJECTPROPERTYEX(@TargetID, 'TableHasPrimaryKey')) = 0
        BEGIN
            RAISERROR(N'Table %s does not have a primary key.', 16, 1, @Target);
        END;

        /* TODO: Check source and target schemas are compatible*/

        DECLARE
            -- Find the primary key columns for the MERGE statement's ON clause
            @PrimaryKeyColumnList nvarchar(max) =
            (
                SELECT
                    STRING_AGG(
                        CONVERT(nvarchar(max),
                            CONCAT(N'S.', QUOTENAME(C.[name]), N'=T.', QUOTENAME(C.[name]))),
                        N' AND ')
                        WITHIN GROUP (ORDER BY IC.key_ordinal)
                FROM sys.key_constraints AS KC
                JOIN sys.index_columns AS IC
                    ON IC.[object_id] = KC.parent_object_id
                    AND IC.index_id = KC.unique_index_id
                JOIN sys.columns AS C
                    ON C.[object_id] = IC.[object_id]
                    AND C.column_id = IC.column_id
                WHERE
                    KC.parent_object_id = @SourceID
                    AND KC.[type_desc] = N'PRIMARY_KEY_CONSTRAINT'
            ),
            @InsertClause nvarchar(max) = N'INSERT (column_list) VALUES (column_list)',
            -- Find the insert columns list
            @InsertColumnList nvarchar(max) =
            (
                SELECT
                    STRING_AGG(
                        CONVERT(nvarchar(max),
                            QUOTENAME(C.[name])),
                        N',')
                        WITHIN GROUP (ORDER BY C.column_id)
                FROM sys.columns AS C
                WHERE
                    C.[object_id] = @SourceID
                    AND C.is_computed = 0
                    AND C.is_identity = 0
                    AND C.is_column_set = 0
                    AND C.is_hidden = 0
                    AND C.generated_always_type = 0
                    AND C.system_type_id != TYPE_ID(N'timestamp')
            ),
            -- Generate the UPDATE SET clause
            @UpdateClause nvarchar(max) = N'UPDATE SET ' +
            (
                SELECT
                    STRING_AGG(
                        CONVERT(nvarchar(max),
                            CONCAT(N'T.', QUOTENAME(C.[name]), N'=S.', QUOTENAME(C.[name]))),
                        N',')
                        WITHIN GROUP (ORDER BY C.column_id)
                FROM sys.columns AS C
                WHERE
                    C.[object_id] = @SourceID
                    AND C.is_computed = 0
                    AND C.is_identity = 0
                    AND C.is_column_set = 0
                    AND C.is_hidden = 0
                    AND C.generated_always_type = 0
                    AND C.system_type_id != TYPE_ID(N'timestamp')
                    AND NOT EXISTS
                    (
                        -- Exclude column if it is part of the primary key
                        SELECT 1
                        FROM sys.key_constraints AS KC
                        JOIN sys.index_columns AS IC
                            ON IC.[object_id] = KC.parent_object_id
                            AND IC.index_id = KC.unique_index_id
                        WHERE
                            KC.parent_object_id = C.[object_id]
                            AND KC.[type_desc] = N'PRIMARY_KEY_CONSTRAINT'
                            AND IC.column_id = C.column_id
                    )
            ),
            -- Basic form of the merge statement
            @MergeStatement nvarchar(max) =
                CONCAT_WS(
                    N' ',
                    N'MERGE @Target AS T',
                    N'USING @Source AS S',
                    N'ON primary_key_match_list',
                    N'WHEN MATCHED THEN merge_matched',
                    N'WHEN NOT MATCHED BY TARGET THEN merge_not_matched',
                    N'WHEN NOT MATCHED BY SOURCE THEN DELETE;');

        -- Substitute the insert column list into the INSERT clause
        SET @InsertClause = REPLACE(@InsertClause, N'column_list', @InsertColumnList);

        -- Substitute other values into the MERGE template
        SET @MergeStatement = REPLACE(@MergeStatement, N'@Target', @Target);
        SET @MergeStatement = REPLACE(@MergeStatement, N'@Source', @Source);
        SET @MergeStatement = REPLACE(@MergeStatement, N'primary_key_match_list', @PrimaryKeyColumnList);
        SET @MergeStatement = REPLACE(@MergeStatement, N'merge_matched', @UpdateClause);
        SET @MergeStatement = REPLACE(@MergeStatement, N'merge_not_matched', @InsertClause);

        BEGIN TRANSACTION;

            IF @Debug = 0
            BEGIN
                -- Peform the MERGE
                EXECUTE (@MergeStatement);
            END;
            ELSE
            BEGIN
                PRINT @MergeStatement;
            END;

        COMMIT TRANSACTION;

        RETURN 0;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
        THROW;
        RETURN -1;
    END CATCH;
END;


Cut specific rows and paste to new workbook faster

For one thing, I think you should do all 20 values all at once, in a single loop. First, create the workbooks so you can access them:

Workbooks.Add
ActiveWorkbook.Name = "value1"
Workbooks.Add
ActiveWorkbook.Name = "value2"

Then you can just check the value against one of the workbook names instead:

transfer_row = 2
Dim Transfer_Value as String
Do Until Range("L" & transfer_row) = ""
    Transfer_Value = Range("L" & transfer_row)
    Select Case Transfer_Value
        Case "value1", "value2"
            Workbooks(old_workbook).Worksheets(old_sheet).Range(transfer_row & ":" & transfer_row).Cut _
                Workbooks(Transfer_Value).Worksheets("Sheet1").Range("A" & new_transfer)
            Workbooks(old_workbook).Worksheets(old_sheet).Rows(transfer_row).Delete Shift:=xlUp
        Case Else
            transfer_row = transfer_row + 1
    End Select
Loop

If you have an array or something with the different values in it, you could use that instead of a massive Case string.


How to handle JSON's undefined value in a better way?

You can define a hash of the possible field names and loop through them:

var fieldTitles = {
    description: "Description",
    Rating: "Average Rating",
    RatingCount: "Rating Count"
};

var volumeInfo = item.volumeInfo;
for (var key in fieldTitles) {
    if (volumeInfo[key]) {
        item_html += '
' + fieldTitles[key] + ':' + volumeInfo[key] +'
';
    }
}

Additional notes:

store item.volumeInfo to a local variable so you don't have to access it through item object all the time.
Most of the time it's better and simpler to check for existence of a value with if (someVar) rather than comparing directly with undefined.


Nice toy! Took me a while to wrap my head around it. It looks ok. The only thing I was thinking about is why not to use std::enable_if as it is much simpler.

#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <set>
#include <vector>
#include <array>
#include <type_traits>

// Detect if container has C::find
template <typename C> decltype(std::declval<C>().find(0), std::true_type{}) test(int);
template <typename C> std::false_type test(...);
template <typename C> using has_find = decltype(test<C>(0));

template <typename C, typename T>
typename std::enable_if<has_find<C>::value, bool>::type contains(const C& container, const T& key) {
    return c.end() != c.find(k);
}

template <typename C, typename T>
typename std::enable_if<!has_find<C>::value, bool>::type contains(const C& container, const T& key) {
    return c.end() != std::find(c.begin(), c.end(), k);
}

int main()
{
    /* */
}


Recursive Method

You can change your GetGCD() method to be much more intuitive and minimal using a ternary operator and recursion. I recommend also documenting what it's doing for readability purposes:

static int GetGCD(int x, int y)
{
    // If y is equal to 0, return x.
    // If y is not equal to 0, recursive call with x as y and y as the remainder.
    return y == 0 ? x : GetGCD(y, x % y);
}

Can also be written as:

static int GetGCD(int x, int y)
{
    // If y is equal to 0, return x.
    if (y == 0)
        return x;
    // If y is not equal to 0, recursive call with x as y and y as the remainder.
    return GetGCD(y, x % y);
}

Depending on your preference.

Iterative Method

As stated in other answers, you might use an iterative method:

static int GetGCD(int x, int y)
{
    while (y != 0)
    {
        int tmp = x % y;
        x = y;
        y = tmp;
    }
    return x;
}

Entry Point

Use TryParse() for retrieving integer input from the console. We don't want exceptions on user input.

Modular arithmetic should be positive. To ensure this, we use the absolute value of the input (Euclidean division). Here's how I would implement it:

static void Main()
{
    int x, y;

    // Get x. Ensure it's an integer.
    Console.WriteLine("Input first number: ");
    while(!Int32.TryParse(Console.ReadLine(), out x));

    // Get y. Ensure it's an integer.
    Console.WriteLine("Input second number: ");
    while(!Int32.TryParse(Console.ReadLine(), out y));

    // Ensure the values being used are positive.
    Console.WriteLine(GetGCD(Math.Abs(x), Math.Abs(y)));

    Console.ReadKey();
}

Output

As you can see, it will wait for an input that can be parsed to an integer and returns the expected value:

Input first number:
a
b
c
585
Input second number:
d
442
13

Benchmark

Just for fun, I thought I'd test the difference between the recursive and iterative methods.

Benchmarked method: Recursive
Test cases: 20
Bench in MS: 184
Iterations per case: 10000000

Benchmarked method: Iterative
Test cases: 20
Bench in MS: 121
Iterations per case: 10000000

The difference is negligible in real application (unless you plan to run this millions of times). These tests were run from entirely different processes.


Read comma separated values and insert in SQL Server 2016 table using String_Split

The following are a few suggestions on how I'd write the stored procedure.

Source Control

If you don't already have a database project, create one in Visual Studio. Then check it in to source control. Microsoft Azure DevOps Services is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.

Error Handling

Use Try, Catch blocks to handle your errors. You can then write them to a log file or table.

Tranactions

Use transactions for rolling back your queries during testing. If a transaction is successful, all of the data modifications made during the transaction are committed and become a permanent part of the database. If a transaction encounters errors and must be cancelled or rolled back, then all of the data modifications are erased.

Common Table Expressions (CTE)

CTE's in your SQL help with documentation. The expression name can then let other developers know why you used that expression e.g. current_suppliers or active_projects.

Merge

If I need to perform more than one DML query on a table, I usually will use a MERGE statement.

Formatting

I would download the following tool for SSMS and Visual Studio, Poor Man's T-Sql Formatter and on GitHub. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.

Here are the settings I used:

Commas

I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier.

e.g. , S.[PersonID]

Estimated Execution Plan

It's a good idea to check the Estimated Execution Plan. The shortcut in Microsoft SQL Server Management Studio (SSMS) is Ctrl + L. You can even run 2 queries in the same tab to compare the plans. Then you can see differences in the query plans using STRING_SPLIT.

Revised SQL

Without table definitions and sample records I was unable to test this, but it should give you a good start.

ALTER PROCEDURE [dbo].[Admin_Save_PMIDS]
      @MemberID INT
    , @PMIDList VARCHAR(MAX)
AS
BEGIN

    BEGIN TRY

        SET XACT_ABORT ON;
        BEGIN TRANSACTION;

            WITH
            pm_ids
            AS
            (
                SELECT
                      [PMID] = Split.a.value('.', 'VARCHAR(100)')
                    , [PersonID] = @MemberID
                    , [MemberID] = @MemberID
                FROM
                    (
                    SELECT CAST('<M>' + REPLACE(@PMIDList, ',', '</M><M>') + '</M>' AS XML) AS String
                    ) AS A
                CROSS APPLY String.nodes('/M') AS Split(a)
            )
            MERGE [dbo].[PublicationTable] AS T
            USING pm_ids AS S
            ON T.[PMID] = S.[PMID] AND T.[MemberID] = S.[MemberID] --< Update the join to the correct unique key for the table
            WHEN NOT MATCHED BY TARGET
            THEN INSERT
            (
                  [PMID]
                , [PersonID]
                , [MemberID]
            )
            VALUES
            (
                  S.[PMID]
                , S.[PersonID]
                , S.[MemberID]
            )
            WHEN NOT MATCHED BY SOURCE --< You may want to add a WHERE clause here
            THEN DELETE
            --OUTPUT @@SERVERNAME AS [ServerName], DB_NAME() AS [DatabaseName], $action, inserted.*, deleted.* --< show the changed records here
            ;

        ROLLBACK TRANSACTION; --< use the rollback for testing
        --COMMIT TRANSACTION; --< use the commit for production

    END TRY
    BEGIN CATCH
        --you can write this to a log table
        SELECT
              [ServerName] = @@SERVERNAME
            , [DatabaseName] = DB_NAME()
            , [ErrorProcedure] = ERROR_PROCEDURE()
            , [ErrorNumber] = ERROR_NUMBER()
            , [ErrorSeverity] = ERROR_SEVERITY()
            , [ErrorState] = ERROR_STATE()
            , [ErrorLine] = ERROR_LINE()
            , [ErrorMessage] = ERROR_MESSAGE()
            , [ErrorDateTime] = GETDATE();

        -- Test whether the transaction is uncommittable.
        IF (XACT_STATE()) = -1
        BEGIN
            PRINT
                N'The transaction is in an uncommittable state.' + 'Rolling back transaction.';
            ROLLBACK TRANSACTION;
        END;

        -- Test whether the transaction is committable.
        IF (XACT_STATE()) = 1
        BEGIN
            PRINT
                N'The transaction is committable.' + 'Committing transaction.';
            COMMIT TRANSACTION;
        END;

    END CATCH

END


Determine if a string has all unique characters

I would suggest an algorithmically better O(n) solution by using a buffer or hashtable or other such structure to record whether or not you have "seen" a character.

For example if you are dealing with a basic string containing char, then you can get away with a bitset of size 256. Each character you see marks a bit. If the bit was already marked, return YES.

Furthermore, if the size of the string you're testing is longer than 256, then that is an automatic NO (not all unique chars) as well.

Since you are dealing with unicode for which the possible values a character can take are very many, then you will want to use a hash table. It will be dramatically faster than even any O(n log n) sorting method.


Maybe you can do it like this:

private const string OAuthTokenUri = "/oauth2/token";

private static string GetOAuthTokenUri(string uriAddress)
{
   Uri result = null;
   return Uri.TryCreate(new Uri(uriAddress), OAuthTokenUri, out result) ? result.ToString() : string.Empty;
}

Please note the slash I have added to OAuthTokenUri.


Creating a Navbar Menu from JSON data with Lodash

You can use Array.prototype.reduce to group items by TAG as the key and using the relationship between PARENT_TAG and TAG.
This approach will give the expected result by running the array only once.

const menuConfig = [{
  ID: 1,TAG: "M:A", PARENT_TAG: "MAIN", TITLE: "A Title"
}, {
  ID: 2, TAG: "AS1", PARENT_TAG: "M:A", TITLE: "A Subtitle 1"
}, {
  ID: 3, TAG: "AS2", PARENT_TAG: "M:A", TITLE: "A Subtitle 2"
}, {
  ID: 4, TAG: "AS3", PARENT_TAG: "M:A", TITLE: "A Subtitle 3"
}, {
  ID: 5, TAG: "M:B", PARENT_TAG: "MAIN", TITLE: "B Title"
}, {
  ID: 6, TAG: "BS1", PARENT_TAG: "M:B", TITLE: "B Subtitle 1"
}, {
  ID: 7, TAG: "BS2", PARENT_TAG: "M:B", TITLE: "B Subtitle 2"
}, {
  ID: 8, TAG: "M:C", PARENT_TAG: "MAIN", TITLE: "C Title"
}, {
  ID: 8, TAG: "CS1", PARENT_TAG: "M:C", TITLE: "C Subtitle 1"
}]

function getMenu() {
  const menu = getItems(menuConfig, 'MAIN');
  console.log(menu);
}

function getItems(items, grandParentTag) {
  const newItems = items.reduce((modifiedObj, currentItem) => {
    const parentTag = currentItem.PARENT_TAG;
    const tag = currentItem.TAG;

    if (!modifiedObj[grandParentTag]) {
      modifiedObj[parentTag] = {};
    }

    if (!modifiedObj[grandParentTag][parentTag]) {
      modifiedObj[parentTag][tag] = {
        title: currentItem.TITLE,
        subMenu: [],
      };
    } else {
      modifiedObj[grandParentTag][parentTag].subMenu.push({
        title: currentItem.TITLE,
      });
    }

    return modifiedObj;

  }, {});

  return Object.values(newItems[grandParentTag]);
}

getMenu();


How to better organize the declarations of these functions?

Structure's ok. The functions are all tightly coupled, which may make changes more of a hassle, but it's nothing super terrible.

It could be cleaner if you separated concerns a bit more. E.g. fetchTags would do only that: Fetch tags, but not append them to the page or anything. And checkScrollLimit would do only that, and just return a boolean instead of calling other functions.

Having fetchTags also append stuff to the page is what leads to attaching the event listener, which causes the circular dependency with scrollingTags, which in turn is coupled to checkScrollLimit which is coupled to fetch.... - you get the idea.

So you could add higher-order functions - say, something like an appendTags function which calls fetchTags and fillTagsList and finally adds the event listener. Then fetchTags wouldn't be coupled to scrollingTags and vice versa; a higher-order function(s) would in charge to tying all the ends together.

Still, I'd say it's mostly a non-issue in this particular case. All your functions are defined before they're called, and that's what matters. The JS runtime doesn't care about the order of the function definitions, only that they have been defined before something tries to call them. So, really, you could mix them up however you want.

Sidenote: The scrollingTags function seems a little too complicated, though, what with wrapping checkScrollLimit in another local function. Could just skip that and call it directly.

On a related note, just your edification: If you had used "proper" function declarations - i.e. function foo() {...} – JavaScript would "hoist" those declarations and interpret them before starting the rest of the script evaluation. So in that case, the code would work even if you actually called a function before it had (seemingly) been defined. So, curiously, this works:

foo();

function foo() { ... } // hoisted; evaluated before anything else

but this doesn't:

foo(); // error: foo isn't defined (yet)

var foo = function () { ... } // not hoisted

and nor do the ES6 => declarations.


I find your variable naming maddening. For example, list is just about the least informative name possible for a list, and str and st are just about the least informative names possible for strings.

The input validation is a bit awkwardly expressed.  Also, if list is null, then it will still crash with a NullPointerException.

The comment is a bit misleading.

The many places where you reset cnt make your code hard to follow.  Without changing your general strategy too much, here's how you could write it better:

public int getGems(List<String> rocks) {
    if (rocks == null || rocks.isEmpty()) {
        throw new IllegalArgumentException("No Input");
    }

    int gemsCount = 0;
    int n = rocks.size();

    // Use list(0) as a source of candidate gems
    char[] candidateGems = rocks.get(0).toCharArray();
    for (char c : candidateGems) {
        int appearances = 0;
        for (String rock : rocks) {
            if (rock.indexOf(c) >= 0) {
                appearances++;
            } else {
                break;
            }
        }
        if (appearances == n) {
            gemsCount++;
        }
    }
    return gemsCount;
}


Shift elements left by n indices in a list

Some suggestions:

The assignment says “ you may assume that n is a non-negative integer”, but the condition you check is “n > 0”. Since n = 0 is non-negative (and corresponds to no mutation of the list), you should handle that as well.
An assert should only really be used to check that the program isn’t in an impossible situation. It would be preferable to use exceptions, and it’s very simple to do so:

if n < 0:
    raise ValueError("Input %d is not a non-negative integer" % n)

(Alternatively, you could implement negative indices as right-shifting, but I’ll leave that for now.)
You can condense the for loop in shift with a list slice: the following code achieves the same effect:

lst[:-1] = lst[1:]

Everything except the last element in lst is assigned to the element one to its left in the original list.

You can extend this list slicing to do away with the temp variable (which is probably a bit more memory efficient), and do the list slicing in a single line. Shifting one position to the left is achieved with the line

lst[:] = lst[1:] + [lst[0]]

At that point, the shift() function is almost so simple that you can do away with it entirely, and recurse only on the shift_left() function. Here’s what I reduced it to:

if n == 0:
    return
else:
    lst[:] = lst[1:] + [lst[0]]
    shift_left(lst, n-1)


It'll add more work if you use interface since your models are different, only one property (Mobile) is the common one, and you'll add Reflection to the equation as well. Even if you used a generic method, you'll add extra work to it. So, in your case, your best approach would be to use overloads (which you've already done) and keep it simple, but you've over-done it. Rather than just duplicating the method and change the model, you'll need to set a private base method, which is going to be used as call back. The other overloads will be set to each process respectively, then it'll callback the base method.

// UserLog overload
internal ResultStatus DownloadsLog(UserLog log)
{
    var parameters = new SqlParameter[]
    {
        new SqlParameter { ParameterName = "@CustomerID", SqlDbType = SqlDbType.NVarChar, Size = 50, Value = log.CustomerId },
        new SqlParameter { ParameterName = "@IsMobile", SqlDbType = SqlDbType.Bit, Value = log.IsMobile },
        new SqlParameter { ParameterName = "@DeviceId", SqlDbType = SqlDbType.Int, Value = log.DeviceId }
    };

    return DownloadsLog("usp_Insert_UserLog", parameters);
}

// NonUserLog overload
internal ResultStatus DownloadsLog(NonUserLog log)
{
    var parameters = new SqlParameter[]
    {
        new SqlParameter { ParameterName = "@DeviceId", SqlDbType = SqlDbType.NVarChar, Size = 50, Value = log.DeviceId },
        new SqlParameter { ParameterName = "@IsMobile", SqlDbType = SqlDbType.Bit, Value = log.IsMobile },
        new SqlParameter { ParameterName = "@AppType", SqlDbType = SqlDbType.NVarChar, Value = log.AppType }
    };

    return DownloadsLog("usp_Insert_NonUserLog", parameters);
}

// base
private ResultStatus DownloadsLog(string procedureName, SqlParameter[] parameters)
{
    using (var dataReader = new SQLHelper(conn).ExecuteReaderStoreProcedure(procedureName, parameters))
    {
        return new ResultStatus
        {
            ResultCode = 1,
            ResultMessage = "Success"
        };
    }
}

as you can see, the UserLog and NonUserLog overloads are there just to set the parameters with the procedure name. Then, I just callback the base method.

Update

This is another approach where you define the parameters and the store procedure name in the model itself, kinda like gathering everything related into one box.

public interface ISqlDbLog
{
    string GetSqlProcedureName();

    SqlParameter[] GetSqlParameters();
}

public class UserLog : ISqlDbLog
{
    public string CustomerId { get; set; }

    public bool? IsMobile { get; set; }

    public int? DeviceId { get; set; }

    public string GetSqlProcedureName() => "usp_Insert_UserLog";

    public SqlParameter[] GetSqlParameters()
    {
        return new SqlParameter[]
        {
            new SqlParameter { ParameterName = "@CustomerID", SqlDbType = SqlDbType.NVarChar, Size = 50, Value = CustomerId },
            new SqlParameter { ParameterName = "@IsMobile", SqlDbType = SqlDbType.Bit, Value = IsMobile },
            new SqlParameter { ParameterName = "@DeviceId", SqlDbType = SqlDbType.Int, Value = DeviceId }
        };
    }
}

public class NonUserLog : ISqlDbLog
{
    public string DeviceId { get; set; }

    public bool? IsMobile { get; set; }

    public string AppType { get; set; }

    public string GetSqlProcedureName() => "usp_Insert_NonUserLog";

    public SqlParameter[] GetSqlParameters()
    {
        return new SqlParameter[]
        {
            new SqlParameter { ParameterName = "@DeviceId", SqlDbType = SqlDbType.NVarChar, Size = 50, Value = DeviceId },
            new SqlParameter { ParameterName = "@IsMobile", SqlDbType = SqlDbType.Bit, Value = IsMobile },
            new SqlParameter { ParameterName = "@AppType", SqlDbType = SqlDbType.NVarChar, Value = AppType }
        };
    }
}

class Program
{
    internal static ResultStatus DownloadsLog(ISqlDbLog log)
    {
        return DownloadsLog(log.GetSqlProcedureName(), log.GetSqlParameters());
    }

    static void Main(string[] args)
    {
        var log = new UserLog
        {
            CustomerId = "Test Customer",
            DeviceId = 5,
            IsMobile = true
        };

        var result = DownloadsLog(log);

    }
}

the advantage of this approach is that you have defined the data mapping within the model, which would be easier to navigate. The other thing, you're also defining the correct SqlDbType mapping. So, instead of using AddWithValue, you will pass the correct datatype, and it's already defined in the model. You can make a generic method where you use Reflection to auto-generate the SqlParameters, all you have to do is to change GetSqlParameters() to :

public SqlParameter[] GetSqlParameters()
{
    return this.GetType()
        .GetProperties()
        .Where(x => x.GetValue(this, null) != null)
        .Select(x => new SqlParameter($"@{x.Name}", x.GetValue(this, null)))
        .ToArray();
}

you can use it as an extension, if you have a wider usage (like applying it to other models as well). like this :

public static class SqlDbExtensions
{
    public static SqlParameter[] ToSqlParameterArray<T>(this T model) where T : ISqlDbLog
    {
        return model.GetType()
            .GetProperties()
            .Where(x => x.GetValue(model, null) != null)
            .Select(x => new SqlParameter($"@{x.Name}", x.GetValue(model, null)))
            .ToArray();

    }
}

This will be applied on all classes that implement ISqlDbLog. This is an insurance. So, with this, you will not need the GetSqlParameter() method in each class nor the ISqlDbLog interface. but you still need ProcedureName.

I hope this would add more helpful thoughts to your work.


A trait class to detect whether a template is specialized for a given type

I think there's an issue with wording here. What you're testing is if a given instantiation of a class template is default constructible. You're not testing if it's "specialized". You cannot check for that. How would you differentiate between:

template <typename T> struct foo { };
template <> struct foo<int> { };

// is foo<X> the primary or the specialization?

Back to your example - just because you cannot construct an object of a particular instantiation (e.g. foo<double>) doesn't mean that you can't name the type. You can do that just fine. That lets you simplify your trait down to:

template <typename, typename=void>
struct is_specialized : std::false_type
{};

template<typename T>
struct is_specialized<T, void_t<decltype(T{})>>
    : std::true_type
{};

Which you would use as is_specialized<foo<int>>::value (true) or is_specialized<foo<double>>::value (false).

But really, since we're just testing for constructibility, we should just use what's in the standard:

template <typename T>
using is_specialized = std::is_default_constructible<T>;


function randNum(limit){var r=Math.floor(Math.random()*limit)+1;return r;}

Can be shortened to:

function randNum(limit){return Math.floor(Math.random()*limit)+1;}

You should also declare your variables outside of the setInterval and then set them inside only if you need to (for example, the days_array never changes so only needs to be decalared once and not every second.


Non-recursive method for finding \$a^n\$

There is a more efficient method using squaring:

int result = 1;
while(n>0){
    if(n%2 == 1)result*=a;
    a *= a;
    n /= 2;
}

Or in recursive notation:

int pow(int base, int exponent) {
     if(exponent == 0) {
          return 1;
     } else if(exponent%2 == 1){
          return base * pow(base*base, exponent / 2 );
     } else {
          return pow(base*base, exponent / 2 );
     }
}

This works because

\$\$ a^n = \begin{cases}
(a^2)^{\frac{n}{2}} & \text{if $n$ is even} \\
a \cdot (a^2)^{\frac{n-1}{2}} & \text{if $n$ is odd}
\end{cases}\$\$


Word VBA Code to Automate Table Captioning

Clean everything up

Code should be written for other people (including future you) to read and understand. A key aspect of this is using consistent rules and conventions for laying out your code.

Indent logic levels, put comments on the same line as the thing being commented (where feasible), use whitespace liberally and consistently.

Same code, much easier to "see", at a glance, what's going on:

Public Sub TestTableCaption()

    Dim strTableType As String
    strTableType = InputBox("Enter 1 for Test Requirements Matrix, 2 for Test Status, or 3 for Test Steps")

    Dim intTableType As Integer
    intTableType = Val(strTableType)
    Select Case intTableType

        Case 1
            strTableType = "Test Requirements Matrix"
        Case 2
            strTableType = "Test Status"
        Case 3
            strTableType = "Test Steps"
        Case Else
            strTableType = ""
            MsgBox ("Entry needs to be 1, 2, or 3. Learn to follow directions, then try again.")
            Exit Sub

    End Select

    strCaption = FindHeading("Heading 3") & " " & strTableType
    strCaption = Replace(strCaption, vbCr, "")
    strCaption = Replace(strCaption, Chr(150), "")
    strCaption = Replace(strCaption, "  ", " ")
    'In theory, Gets rid of dash from title. Doesn't actually work.

    'MsgBox (strCaption)
    Call GenerateCaption(strCaption, "Table")

End Sub

And now we can immediately see that your sub has 4 distinct sub-sections:

Get user input number
Convert number to the appropriate table style
Find the relevant table heading and clean the text a bit
Call GenerateCaption with the (now cleaned) caption text.

This leads us to the next key idea:

Refactor Mercilessly

Refactoring is the process of taking some set of operations, and abstracting them into their own Sub/Function. This makes your code cleaner, easier to follow, easier to modify and more re-usable.

Let's take this a step at a time.

Step 1: Get the user input string.

What are our requirements? The user needs to indicate which of 3 table types to change by inputting a number from 1 to 3.

First, a Descriptive, Unambiguous, name:

Public Function TypenumFromUser() As Long

Second, get input.

    Dim userInput As String
    userInput = InputBox("Enter 1 for Test Requirements Matrix, 2 for Test Status, or 3 for Test Steps")

Third, validate Input. Input must be a number. And it must be 1, 2 or 3. If the input is invalid, let's prompt the user to try again.

Public Function TypenumFromUser() As Long
    '/ User must input a table type as a number
    '/ Current options are 1, 2 or 3
    '/ If the input is invalid, prompt the user to try again

GetNewInput:
    Dim userInput As String
    userInput = InputBox("Enter 1 for Test Requirements Matrix, 2 for Test Status, or 3 for Test Steps")

    Dim intCheck As Long
    On Error GoTo BadUserInput
        intCheck = CLng(userInput)
    On Error GoTo 0

    Dim isValidInput As Boolean
    isValidInput = False
    If IsWholeNumber(intCheck) Then
        If intCheck >= 1 And intCheck <= 3 Then
            isValidInput = True
        End If
    End If

    If isValidInput Then
        TypenumFromUser= intCheck
    Else
        GoTo BadUserInput
    End If

CleanExit:
    Exit Function

BadUserInput:
    MsgBox "Input must be a whole number from 1 to 3. Please try again."
    GoTo GetNewInput

End Function

Public Function IsWholeNumber(ByVal checkNum As Variant) As Boolean
    '/ First check that input is a number.
    '/ Then round to the nearest whole number.
    '/ If the rounded number is the original number, then it is a whole number

    IsWholeNumber = False
    If IsNumeric(checkNum) And (Math.Round(checkNum, 0) = checkNum) Then
        IsWholeNumber = True
    End If

End Function

Sure, it's a bit verbose, but now you never need to touch this function again. And if your inputs change, you know exactly where to go to change things.

You've also now got an IsWholeNumber function which you can use in other projects down the line. You should build these utility function up over time and before long, you'l have a whole module full of useful little functions that you can import into any new project.

Now, your sub looks like this:

Public Sub TestTableCaption()

    Dim intTableType As String
    intTableType = TypenumFromUser
    Select Case intTableType

        Case 1
            strTableType = "Test Requirements Matrix"
        Case 2
            strTableType = "Test Status"
        Case 3
            strTableType = "Test Steps"
        Case Else
            strTableType = ""
            MsgBox ("Entry needs to be 1, 2, or 3. Learn to follow directions, then try again.")
            Exit Sub

    End Select

    strCaption = FindHeading("Heading 3") & " " & strTableType
    strCaption = Replace(strCaption, vbCr, "")
    strCaption = Replace(strCaption, Chr(150), "")
    strCaption = Replace(strCaption, "  ", " ")
    'In theory, Gets rid of dash from title. Doesn't actually work.

    'MsgBox (strCaption)
    Call GenerateCaption(strCaption, "Table")

End Sub

Step 2: Convert input to a table typestring

This is also begging to be refactored into a function. TypestringFromTypenum.

Public Function TypestringFromTypenum(ByVal typeNum As Long) As String

    Dim typeString As String

    Select Case typeNum

        Case 1
            typeString = "Test Requirements Matrix"
        Case 2
            typeString = "Test Status"
        Case 3
            typeString = "Test Steps"
        Case Else
            GoTo BadInput

    End Select

CleanExit:
    TypestringFromTypenum = typeString
    Exit Function

BadInput:
    MsgBox "Unexpected Input Error. See Debug."
    Debug.Print "The following should be 1, 2 or 3: " & CStr(typeNum)
    Resume CleanExit

End Function

Now, if you have to add another input, all you have to do is add 2 lines here, modify the input validation, and you don't even have to touch the rest of your code.

And now, we should roll this together with TypenumFromUser. Like so:

Public Function TypestringFromUser() As String

    Dim typeNum As Long
    typeNum = TypenumFromUser

    Dim typeString As String
    typeString = TypestringFromTypenum

    TypestringFromUser = typeString

End Function

With TypenumFromUser and TypestringFromTypenum as above.

Now your sub looks like this:

Public Sub TestTableCaption()

    Dim tableTypeString As String
    tableTypeString = TypestringFromUser

    strCaption = FindHeading("Heading 3") & " " & tableTypeString
    strCaption = Replace(strCaption, vbCr, "")
    strCaption = Replace(strCaption, Chr(150), "")
    strCaption = Replace(strCaption, "  ", " ")
    'In theory, Gets rid of dash from title. Doesn't actually work.

    'MsgBox (strCaption)
    Call GenerateCaption(strCaption, "Table")

End Sub

With the rest nicely abstracted away.

Step 3: I'm not very familiar with the Word Object Model, so I'm going to leave FindHeading alone. Though I would rename it to GetTableHeading.

Step 4: Clean heading Text.

This absolutely needs to be its' own function. CleanTableHeading

Public Function CleanTableHeading(ByVal heading As String) As String
    '/ Remove carriage returns
    '/ Remove dashes
    '/ Reduce multi-spaces to single spaces

    Dim cleanString As String

    cleanString = heading
    cleanString = Replace(cleanString, vbCr, "")
    cleanString = Replace(cleanString, "-", "")

    Dim hasMultiSpaces As Boolean
    hasMultiSpaces = (InStr(cleanString, "  ") <> 0)
    Do Until hasMultiSpaces = False
        cleanString = Replace(cleanString, "  ", " ")
        hasMultiSpaces = (InStr(cleanString, "  ") <> 0)
    Loop

    CleanTableHeading = cleanString

End Function

You ever need to add another paramater to your string cleaning? Just come straight here, change it once and you're done.

Your main sub now looks like this:

Public Sub TestTableCaption()

    Dim tableTypeString As String
    tableTypeString = TypestringFromUser

    Dim tableHeading As String
    tableHeading = FindHeading("Heading 3") & " " & tableTypeString

    Dim cleanHeading As String
    cleanHeading = CleanTableHeading(tableHeading)

    GenerateCaption cleanHeading, "Table"

End Sub

Much easier to work with.

Performance

Rule #1 of performance optimisation: Benchmarking.

I guarantee you that 95% of your operations run in a fraction of a second. There will be one sub/function/loop somewhere which is taking up the other 40 seconds. In order to fix it, you must first find it.

Simple Option: Just Debug.Print "[Position]: " & NOW() throughout your code. Like so:

Public Sub TestTableCaption()

    Debug.Print "ExecutionStart: " & Now()

    Dim tableTypeString As String
    tableTypeString = TypestringFromUser
    Debug.Print "Got TypeString From User: " & Now()

    Dim tableHeading As String
    tableHeading = FindHeading("Heading 3") & " " & tableTypeString
    Debug.Print "Found Table Heading: " & Now()

    Dim cleanHeading As String
    cleanHeading = CleanTableHeading(tableHeading)
    Debug.Print "Cleaned Table Heading: " & Now()

    GenerateCaption cleanHeading, "Table"
    Debug.Print "Generated Caption: " & Now()

End Sub

Run that, and you'll get a nice printout in the immediate window of how long each sub/function took to execute.

Once you know where the problem code is, post that as its' own separate performance question here or on Stack Overflow. (I recommend here).

That aside, some very basic VBA performance improvements:

Public Sub MainSub()

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.StatusBar = False

    ...

    Code

    Code

    Code

    ...

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.StatusBar = True

End Sub


Naming and interface

Please avoid mixing English (calculate-distance) with Portuguese (raio).  The code should be in English; write your comments in whatever language you prefer.

ltd and lgt seem like awkward abbreviations; lat and lon or lat and lng seem more conventional.  The latter is what Google uses for the Maps and Android APIs, for example.

Putting "calculate" in the name of a function seems redundant, especially in a functional programming language.

One of the most surprising behaviours is that your function gives the result in meters, even though your raio constant is in kilometers.  To discover that quirk, you would have to scroll all the way to column 219 at the end of the function, at the end of a very long line of code!  A better comment on the function would help; better naming would be beneficial as well.

Implementation

As I mentioned, those are very long lines of code — almost unreadable.  It would be more readable if you broke down the calculation into subexpressions.

In fact, (+ (Math/pow (Math/sin (/ delta-latitude 2)) 2) (* (Math/cos (Math/toRadians (:source/ltd source))) (Math/cos (Math/toRadians (:to/ltd to))) (Math/sin (/ delta-longitude 2)) (Math/sin (/ delta-longitude 2)))) is a common subexpression that you evaluate twice.  So, not only is your code unreadable, it's also inefficient.

I would convert the latitudes and longitudes to radians right away, since degrees are useless for trigonometry.  Half the difference in angles are easily recognizable quantities.  Defining the \$\sin^2(\theta)\$ function as a lambda is also useful.

(def earth-radius-km 6372.795477598)

(defn distance
    "Calcula distância entre duas coordenadas geográficas em metros"
    ([latlng1 latlng2]
        {:pre [every? (every-pred map? #(contains? % :lat) #(contains? % :lng)) [latlng1 latlng2]]}
        (let [lat1 (Math/toRadians (:latlng1/lat latlng1))
              lng1 (Math/toRadians (:latlng1/lng lnglng1))
              lat2 (Math/toRadians (:latlng2/lat latlng2))
              lng2 (Math/toRadians (:latlng2/lng lnglng2))
              half-dlat (/ (- lat2 lat1) 2)
              half-dlng (/ (- lng2 lng1) 2)
              sin2 (fn [x] (Math/pow (Math/sin x) 2))
              a (+ (sin2 half-dlat) (* (Math/cos lat1) (Math/cos lat2) (sin2 half-dlng)))]
             (* 2000 earth-radius-km (Math/atan2 (Math/sqrt a) (Math/sqrt (- 1 a)))))))


I'd say, your call to Apple.GetPlayerManager() bothers me. Your socket implementation does not need to know this is a game and it's creating a new player etc. I whould break the relation somehow, passing the payload or event received in your socket to some other service, preferably injected using dependency injection or sth.

This would make your socket class testable on its own (by mockup objects) and other classes much easily.

PS: your SocketSettings class is actually ServerInformation, copy/paste problem I suppose..


Overall this looks pretty good. Just a couple of things come to mind:

Square.js

The setSymbol method should throw errors instead of returning strings, especially since I don't see any place where those strings are handled in a manor allowing the user to correct their mistake.
The error message when the square is occupied just needs a slight grammatical correction: This square is already filled (filled instead of filler)

TTTGame.js

Create all methods on the prototype. You aren't using any private function scope variables, so putting the methods on the prototype will be more efficient.

General Comments

The name TTTGame is kind of obtuse. I know it is probably an abbreviation for "Tick Tack Toe Game" but I think a more descriptive name is in order. All around, throwing these classes into a namespace would be useful. Consider the semantic differences between these two sets of classes:

Square (is it a tick tack toe square or a two dimensional representation of a plane in mathematics)
Board (Diving board? Game board? Discussion board?)
TTTGame (What does TTT stand for?)

Vs:

TickTackToe.Square
TickTackToe.Board
TickTackToe.Game

No explanation necessary for the second set of class names.

All in all, this looks pretty good.


You can use the order of XML nodes as field order:

<importformat>
    <firstname/>
    <middlename/>
    <lastname/>
</importformat>

and parse it like that:

public static string[] GetFieldsOrder(string xmlContents)
{
    return XElement.Parse(xmlContents)
        .Elements()
        .Select(element => element.Name.LocalName)
        .ToArray();
}


Looks good, follows the laws of Applicative AFAICT, and I'd leave it like this, with fmap you'd need to write more.


Hiding odd rows in a table on click event

Your JavaScript is OK, but beware of writing code where you can get away without it.  In this case, there is a CSS3 :nth-child() selector1 that lets you select odd rows without tagging them manually with class="hide".

You just have to trigger the CSS rule when the button is pressed.  Note that if you want to select one specific element in a document, it's better to mark it using id="…" and select it using document.getElementById(…) — that's exactly what it is designed to do, and browsers will optimize ID lookups to be as fast as possible.

/* hideOddRows.js */
document.getElementById('HideRows').onclick = function hideRows() {
    document.getElementsByTagName('table').item(0).className = 'odd-rows-hidden';
}
table.odd-rows-hidden tr:nth-child(odd) {
    display: none;
}
<!DOCTYPE html>

        <title>Hide odd rows</title>
        <meta charset="UTF-8">

                row 1

                row 2

                row 3

                row 4

                row 5

        <button type="button" id="HideRows">Hide Odd Rows</button>

1 Caveat: requires Internet Explorer ≥ 9.  If you need to support older versions of IE, you'll probably want jQuery.


Optimizing an implementation of the RKF method

All these lines are really weird:
a4  =   9.230769230769231e-01  #  12/13

Unless you have a good reason (which I'd then state in the code as a comment) to do that, just write a4 = 12/13 instead.
Gonna be the same anyway:
>>> import dis
>>> dis.dis('a4 = 12/13')
  1           0 LOAD_CONST               0 (0.9230769230769231)
              2 STORE_NAME               0 (a4)
              4 LOAD_CONST               1 (None)
              6 RETURN_VALUE
>>> dis.dis('a4 = 9.230769230769231e-01')
  1           0 LOAD_CONST               0 (0.9230769230769231)
              2 STORE_NAME               0 (a4)
              4 LOAD_CONST               1 (None)
              6 RETURN_VALUE

This line for example is not right:
b51 =   2.032407407407407e+00  #  439/216

The values differ slightly, your value being less accurate:
>>> 2.032407407407407e+00
2.032407407407407
>>> 439/216
2.0324074074074074


As for the jQuery/function usage, there is definitely room for improvement but it would be helpful to see an example HTML element that contains the article img, title, and url to understand the page structure a bit.
I think your variable names are clear, but could be simplified. Also, it is common practice to use Camel Case with the first letter lowercase for Node/Javascript instead of underscores between words.

For example, replace number_of_articles_beforehand with numArticlesBefore

Here is an article I found helpful regarding var, let, const

https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75
Javascript allows variable hoisting (click here for more info) with the keyword var whereas variables/identifiers declared as let or const do not hoist.
Personally, I have stopped using var altogether to help improve code readability as mentioned in the article above. Also, it is common practice to use const for the Node package require statements instead of var.
Remove the var title, url, image; line because you are only using those variables within their respective functions.
Lastly, I would encourage you to replace i = i + 1; with i++;. It does the same thing and is easier to read. (FYI, i--; would decrement i by 1).


All permutations with known letter on one place

Usually, when you find yourself with multiple nested loops doing functionally the same thing, that's a good time to look for a solution using recursion, which are functions (you could indeed use generators) calling themselves.

So, you've got a list of characters c.
For the first letter, you pick from c.
For the second letter, you pick from c except that you can't choose the first letter.
For the third letter, likewise but letters 1 and 2 are banned.
And so on.

It should be clear that each of those is doing the same thing, it's just using a different set of allowed letters. That means you can use the same function for the job, and have it take as a parameter the letters that it's allowed to use.

There are two advantages to such a function over your implementation (although you could patch your version easily enough, it would involve writing even more duplicate code)

Firstly, at each step in my description, I rule out impossible options straight away. In your version, i and j will both be the first element of c straight away which is clearly a waste of time, but you don't check until you have looped through k, l, and m too. It would be better to move on to the next j as soon as it becomes clear that you can't use it. (And likewise with the others)

Secondly, your version is very specific to your input c. It's fine so long as c is exactly 5 long and only contains each letter once. If c contains any double letters you won't find any permutations at all. They'd all get swallowed up because python wouldn't know that they're meant to be different 'e's or whatever. Likewise if c was not 5 characters long, your code would not give a permutation. The recursive functional approach avoids both of those problems, and so is much more flexible.

Alternatively, as Peilonrayz suggests, look for the same code that someone else has written. itertools has permutations as well as combinations. The known letter thing is easy enough: you loop through permutations of the remaining characters, and for each one you print out the prefix, the 'u', and the suffix.

for perm in itertools.permutations(c):
    print (perm[0] + perm[1] + 'u' + perm[2] ...)

If you're a professional programmer, "use the library someone else wrote" is usually the best answer. It's just worth knowing the above so you can understand what's going on, including under the hood of the library function.


Your code can be simplified with only awk script:

awk '/exon/ {gsub("[\";]","", $10);print $1,$4,$5,$7,$10}' file.gtk

gusb removes any occurrence " or ; in the 10th element.


Formatting a possibly nil value as hours and minutes

In one line

def length
  (len = read_attribute(:length)) && "#{(len/60/60).floor}h #{len.modulo(60*60)/60}m"
end

If len == nil return nil, if not - second operand


Loading a database table using a promise chain

Having a catch at the very end is fine. This assumes that your errors weren't recovered or handled midway.

Promise.reject('foo').then(v => console.log(v), e => console.log(e)).catch(e => console.log(e));
> foo // from `then`

In the code above, the Promise failed. However, it had a chance to recover via then's reject handler. Thus, the promise returned after that is actually resolved rather than rejected, causing catch to not execute. To log those recoveries, do a console.log at the recovery site instead, and not rely on catch.

As for the rest of your code

I suggest you generate your query using template strings. That way, you avoid ugly string concatenation. Note that template strings use backticks (``).

I also suggest you just create a connection and leave it open. There is some overhead in creating a connection, you'd want to avoid that especially when you hit the DB hard.

Your MySQL driver appears to already use Promises. No need to wrap the entire thing in a Promise. Simply return the object created by the API.

// Assuming connection is a promise from a connect()
return connection.then(() => request.query(query)).catch(err => {
    console.log(err);
    throw err;
});


Closeable to AutoCloseable converter utility for 3rd party java libs

I'll try to say this the best way I can...

Completely useless unnecessary!

Sorry. I couldn't find any better way to say it. The code that you have is well-written, but it is not necessary in the first place.

The reason is that the interface Closeable already lists AutoCloseable as a "superinterface", which means that Closeable extends AutoCloseable. So all Closeable objects are already AutoCloseable.

Which means that your code:

try (AutoClose<SomeType> auto = AutoClose.of(someCloseable)) {
    auto.instance.someWork();
}

Can instead be simply:

try (SomeType auto = someCloseable) {
    auto.someWork();
}

There is no need for your AutoClose wrapper.


Parallel SQL queries using completable future

Yes, your approach is correct.

However, you parallelize various queries, which probably go to a remote backing database. As you told us nothing about the runtime of these queries, the nature of the database, the complexity of the underlying statements, I can only ask you to measure.

Parallelism induces overhead - in the runtime AND in program complexity. Check, whether it is worth it, and where your bottlenecks lie.

In my experience from enterprise applications, real big data transfers are normally not made better by parallelism, as the bottleneck is often the network between application server and database.


Implement integer exponentiation faster than repeated multiplication

The solution 1 is still a repeated multiplication. The only difference is that the multiplication is implemented as a repeated addition:

    for (let j = 1; j < x; j++) {
        tmp += res;
    }

is a very long way to say

    tmp = res * x;

and obviously it doesn't make the code any faster.

The second solution is almost correct. It fails for negative y (negative is still integer!), and the handling of pow2(0, 0) is questionable.

Besides that, try to avoid the recursion; recursive calls are expensive, and the goal of the exercise is to achieve the maximal speed. There does exist a true honest-to-goodness iterative algorithm.


Your algorithm is a variant of Fisher-Yates shuffle,
and it's a good algorithm to shuffle a collection.
A more common form is instead of using the last element to swap,
you could have used the decreasing index i to swap,
like this:

  for (var i = len; i > 0; i--) {
    rnd = Math.floor(Math.random() * len);
    temp = array[rnd];
    array[rnd] = array[i];
    array[i] = temp;
  }

It doesn't matter much though, your version is fine too.

Something to improve is a bit cosmetic:
it would be better to name your function with lowercase letters, shuffle,
because it's customary to start with a capital letter only functions that are used to create objects with the new keyword.

Lastly, this is a bit tedious to type:

var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];

You could use this shorter form instead:

var arr = "abcdefghi".split("");


Connect to MySQL and fetch a list of customers asynchronously using C#

In Get() you do not need to wrap the call to GetAllCustomers() into a Task because it's already asynchronous:

public async Task<HttpResponseMessage> Get()
    => await GetAllCustomers();

There is, however, something else to do:

GetAllCustomers() should be renamed GetAllCustomersAsync() to inform that it's an asynchronous method.
GetAllCustomersAync() should not be responsible to create the HttpResponseMessage because you want to test DB logic separately from controller logic. More on this later.
You do not need to return an HttpResponseMessage, simply return the strongly typed model/view model you're interested to.

In code:

public async Task<DataTable> Get()
    => await GetAllCustomersAsync();

Now you have to change GetAllCustomersAsync() to match the above.

Outside a fictional example (or an extremely simple application) I'd avoid to directly return DataTable and I'd move to a proper data layer. You usually do not want to handle SQL code directly in your business logic, especially because:

It's error-prone.
UI requirements may change over time but database may be stable.
Database may change over time but UI may be stable.
You do not have any compile-time check.
It's hard to test business logic without a database.

According to usual C# naming conventions local variables are camelCase, Customers should be customers.

You do not need to close a connection if it's wrapped within a using statement, disposing the connection will also close it.

Even assuming you do not return the model type, for example:

public IHttpActionResult Get()

You do not need to go through the ControllerContext.Request.CreateResponse() thing, simply:

public IHttpActionResult Get()
{
    return Ok(new { Customers });
}

In your catch clause ex.Message.ToString(); is doing nothing. If you properly had DB logic in a separate layer (let's say in a class DatabaseServices just to give a name) you may want to:

catch (MySqlException e)
{
    throw new DatabaseException("Cannot read customers", e);
}

Where DatabaseException is a custom exception you use through your data layer. Your controller (simplified without async stuff):

public IHttpActionResult Get()
{
    try
    {
        using (var db = new DatabaseService())
            return Ok(new { Customers = GetAllCustomers() });
    }
    catch (DatabaseException e)
    {
        return InternalServerError(e);
    }
}

Of course in real world there will also be some logging here and there and some logic to recover from known errors...

Jumping back to your query method, it might be simplified little bit:

using (var con = new MySqlConnection("..."))
using (var cmd = new MySqlCommand("SELECT * FROM Customers", con))
{
    try
    {
        await con.OpenAsync();

        var sda = new MySqlDataAdapter(cmd);
        var customers = new DataTable();
        await sda.FillAsync(customers);

        return customers;
    }
    catch (MySqlException ex)
    {
        // ...
    }
}

You do not need to check if connection is closed for a newly created MySqlConnectionObject(), it can't happen and your code wil always work as expected but if it was not the case then you will return an empty DataTable.

Note that when code will grow and you will probably need a better way to build SQL commands (assuming you won't use an ORM). Very first step is to, at least, move them outside in private const string fields.


Constructor function for persons with hobbies

Performance

Strings are immutable, so using accumulator += stuffToAppend in a loop can traditionally impact performance. The problem is that we're creating a new string every iteration, leading to quadratic time complexity for an operation that should be linear. It turns out that modern browsers optimize this heavily using an internal array to represent string parts and make it quite fast over using an explicit array, so this post is focused on style rather than performance.

Design

On first thought, reduce seems like the right function from a semantic standpoint since we want to boil the array of interests down to one string. However, since avoiding string concatenation requires an intermediate array in reduce, we might as well just skip the intermediate array and use map and join. It's pretty common that reduce can be replaced with map or filter, which are more specific and succinct.

Switch statements are also generally not used much in JS (but often used in C...). You can replace many switch statements in JS with an object (particularly if you're choosing between a number of similar functions), or at least an if statement. Either way, the nature of the commas and "and" in this example makes it a bit awkward, so there doesn't seem to be any clear-cut win.

Additionally, this routine of "prettifying" a list is generic and can be moved to a separate function to keep Person clean.

As an aside, instead of switching between "interests", "hobbies" and "bio", it seems best to pick one term and stick with it throughout.

Here's my attempt. This might seem a bit abstract, but it's typical in JS to avoid conditional/switch stuff as much as it is to avoid loops (which is the idea with reduce). If you prefer a more traditional approach, replace the joins array and indexing with an if statement and I'd still endorse it.

const prettyList = (a, sep=", ", endSep=[" and ", "."]) =>
  a.map((e, i) => e + (endSep[endSep.length-a.length+i] || sep)).join("")
;

const Person = function (interests=[]) {
  this.interests = interests;
  this.interestsSentence = prettyList(interests);

  this.interestsStr = () =>
    "This person's interests are: " + this.interestsSentence
  ;
};

const interests = ["foo", "bar", "baz", "quux"];

for (let i = 1; i <= 4; i++) {
  console.log(new Person(interests.slice(0, i)).interestsStr());
}

Now the function is reusable and we can change its behavior without much effort at all:

const prettyList = (a, sep=", ", endSep=[" and ", "."]) =>
  a.map((e, i) => e + (endSep[endSep.length-a.length+i] || sep)).join("")
;

const activities = ["biking", "running", "walking", "skipping", "driving"];
console.log("I love", prettyList(activities, "; ", [", sometimes ", " but not ", "!"]));
console.log("I love", prettyList(activities, " and ", [" while ", " :-o"]));


First I would like to say, congratulations on stepping out of the Microsoft bubble!

To begin, most PHP functions are very similar (if not exactly the same) to their linux counterparts. Some of them even just directly call their linux counterparts and return the result.  You don't have to know linux shell script to know PHP (or vice versa) but it definitely helps and knowing that there is a deeply connected relationship between the two is a enlightening.

PHP has a few global variables that you should familiarize yourself with:

$_POST: holds any POST data sent with the request
$_GET: holds any GET data sent with the request
$_SESSION: holds the session data

My first recommendation for you is to use the $_POST variable instead of using file_get_contents("php://input").

I have to be honest, in all my years of PHP development, I've never used file_get_contents("php://input") for anything. I didn't even know what that did when I read this post. I had to look it up so that I could answer intelligently.  All the POST data will be nicely, and automatically, placed into the $_POST array for you every single time.

My second recommendation for you is to checkout the PHP function empty().  This can be used on arrays with any key, even if the key doesn't exist, to check either if the key actually exists or if the key has an empty value.  It's great for an initial check on POST data.

So for example, you could replace:

if(!property_exists($json_data, "MethodName") || is_null($json_data->MethodName) || function_exists($json_data->MethodName . "()"))

with

if(empty($_POST['MethodName']))

Pretty neat right?

The only caveat with this function is that it will return true not only if the array index doesn't exist, but also if the value at the array index evaluates to false ("", 0, array(), null, etc...).   If you need to handle values that evaluate to false differently than you can use isset() either in addition to or instead of empty() which will tell you if the key is set, regardless of whether the value is an empty value or not.

So basically, $_POST, empty(), isset() are your bread and butter for form data processing in PHP.  Use them wisely.  :)

You should also check out unset()([http://]php.net/manual/en/function.unset.php), which lets you unset keys in your data arrays, for example, to remove keys that are set but have empty values that you'd rather just not be in the array at all.


I was in the process of answering your question on StackOverflow but it was moved to Code Review -- so I'll answer it here.

You might be able to avoid using switch or multiple if conditions if you build a data structure that fits your needs.

$(function() {

  // data structure
  var products = {
    bAll: {
      rose: {
        name: 'Rose',
        countries: ['US(1)', 'USA(2)', 'Canada(3)', 'China(4)']
      },
      tulip: {
        name: 'Tulip',
        countries: ['US(1)', 'USA(2)', 'China(4)']
      }
    },
    b1: {
      rose: {
        name: 'No. 1 Rose',
        countries: ['US(1)', 'USA(2)']
      },
      tulip: {
        name: 'No. 1 Tulip',
        countries: ['US(1)']
      }
    },
    b2: {
      rose: {
        name: 'No. 2 Rose',
        countries: ['USA(3)', 'China(4)']
      },
      tulip: {
        name: 'No. 2 Tulip',
        countries: ['USA(3)', 'China(4)']
      }
    }
  };

  $(document).on("input", "#intBrand, #intProcudt", function() {

    var intBrand = $('#intBrand').val();
    var intProcudt = $('#intProcudt').val();

    // using the data structure, it makes it much easier to get information

    // get product
    var product = products[intBrand][intProcudt]['name'];

    // get rose countries
    var roseCountries = products[intBrand]['rose']['countries'];

    // get tulip countries
    var tulipCountries = products[intBrand]['tulip']['countries'];

    // build HTML string using product's rose countries
    var roseP = roseCountries.map(function(country) {
      return product + ' from ' + country;
    }).join('
');

    // build HTML string using product's tulip countries
    var tulipP = tulipCountries.map(function(country) {
      return product + ' from ' + country;
    }).join('
');

    $('#allRoseItems').html(roseP);
    $('#allTulipItems').html(tulipP);
  });

  $("#intBrand").trigger("input");

  // alternate way is to get the data from a JSON file
  // instead of having the large data in our file;

  // you would need to wait for the response from the $.getJSON
  // before triggering the initial load automatically

  /*
  var products;
  $.getJSON('path/products.json', function (res) {
      // store the data, so that we can use it
      products = res;
      // trigger initial oninput
      $("#intBrand").trigger("input");
  });
  */
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">

    Select Brand:

    <select id="intBrand" name="intBrand" required>
      <option value="bAll">All items</option>
      <option value="b1" selected>Brand 1</option>
      <option value="b2">Brand 2</option>
    </select>

    Select Product:

    <select id="intProcudt" name="intProcudt" required>
      <option value="rose">Rose</option>
      <option value="tulip">Tulip</option>
    </select>

You should also cache your jQuery objects if you are going to be re-using them. There's no need to search the DOM every time.