A "todo" app built to practice Object Oriented JavaScript

First, your markup. From first look, it looks like a loose set of elements. I cannot tell which parts are which immediately. One method you can use is BEM. It's primarily a CSS naming convention, but can easily be used to identify which elements belong to a group.

TODO List

  UNDO

something

  <form class="todo__form>
    <input class="todo__input" type="text" placeholder="Enter your tasks here...">
    <input class="todo__submit" type="submit" value="add">
  </form>

In this case, you have a todo block. Inside this todo block you have todo__element. If these elements have alternate states or styles from their default, you have todo__element--alternate. Simple naming convention.

This leads us to the next issue, CSS. First, the way you write CSS is very generic. You're styling using element selectors. This is fine if the app is isolated, but if you do this inside a bigger app, you risk affecting other elements not related to the todo list.

.todo{...}
.todo__header{...}
.todo__undo{...}
/* and so on */

In this case, in conjunction with the BEM naming convention, you can easily target elements with class names. They all have the same specificity since they're all classes, and you can easily identify which groups of styles belong together and which groups of elements they affect.

Before we head over to JS, I notice that you have UNDO. Instead of putting a blank inline script on href, I suggest you put # and use event.preventDefault() in the click handler to prevent it from navigating. This is so that all your JS live in JS, not mixed anywhere.

Now in JS, I notice that you don't keep track of state in the script. You submit a todo, directly append to the DOM, and that's it. JS knows nothing about the todo items afterwards and state is held in the DOM. This works in small scale, but this becomes tricky when the app scales, when you do more data manipulation like item counts, multiple undos and that sort of stuff.

Following MVC and similar variations, data should live in the data layer, or just some sort of storage like a variable. View is the UI, a visual representation of the data in the model. Controller accepts interaction, usually the place where handlers and logic are written. You don't need overly complex code, but it's nice to have them clearly separated.

(function(){

  var todoList   = document.querySelector('.todo__list');
  var todoSubmit = document.querySelector('.todo__submit');
  var todoInput  = document.querySelector('.todo__input');
  var todoUndo   = document.querySelector('.todo__undo');

  // Our "model", which is just some data storage
  var todos = [];

  // Our "controller", where all the logic goes
  function createTodo(item){
    // Return a todo object
  }

  function removeTodo(index){
    // Remove todo from todos at index
  }

  function addTodo(todo){
    // Add todo to todos
  }

  function renderTodos(){
    // For each item in todos, render an

    // Add or remove from the DOM accordingly.
  }

  todoSubmit.addEventListener('click', function(){
    // get input value
    // createTodo
    // addTodo
    // clear input
    // renderTodos
  });

  todoUndo.addEventListener('click', function(){
    // get last todo
    // removeTodo
    // renderTodos
  });

}());

In the really abstract sample above, you can see that todos is the source of truth, the "model". renderTodos simply renders that array. That plus your initial DOM constitutes your "view", the UI. The controller is the logic, from the handlers to the utility functions. The only time the JS has to know about the DOM is in renderTodos. Everything else is just JS, arrays and objects. You can easily determine the number of items by getting the array length and adjust your render function accordingly.

Now you may wonder, the delete button is dynamically generated with the todo, but how would you bind if renderTodo should only construct DOM? How would the controller bind to it? That's where event delegation comes in. Events "bubble" up the DOM. Click a descendant element, the ancestors also count as clicked. We can attach an event on a parent item to listen for future elements.

// Attach event handler to todoList (the ul)
todoList.addEventListener('click', function(event){
  // check if event.target is the delete button from an li
});


A shorter form of Trevor's answer (but essentially doing the same thing):

public static IEnumerable<T> Circle<T>(this IEnumerable<T> list, int startIndex)
{
    return list.Skip(startIndex).Concat(list.Take(startIndex));
}

This will still lazy evaluate just like Trevor's answer, because Concat lazily evaluates.

Further more, if you have written a method to cycle through an IEnumerable, why not call it Cycle?

Lastly, I'd actually recommend taking advantage of lazy evaluation to give you a more useful method. The one below will continue to cycle indefinitely, starting with an optional index:

public static IEnumerable<T> Cycle<T>(this IEnumerable<T> list, int index = 0)
{

    var count = list.Count();
    index = index % count;

    while(true)
    {
        yield return list.ElementAt(index);
        index = (index + 1) % count;
    }
}

Then you can do something like:

foreach(var num in Enumerable.Range(1, 10).Cycle(4).Take(30))
{
    Console.WriteLine(num.ToString());
}

And this lets you specify just how many repeated items you want.


Avoid static initializer for lists of image and video formats?

According to your comment,
if it's only the MultipartFileWrapper.class.getField("multipartFile") statement that might throw a NoSuchFieldException,
then when that happens, the lines that set imageFormats and videoFormats will not be reached, so these values will remain null, and the if conditions in the catch block are pointless.

Furthermore, it's good to minimize the scope of try-catch blocks.
Consider this reworked version:

static {
    Field multipartFileField = null;
    try {
        multipartFileField = MultipartFileWrapper.class.getField("multipartFile");
    } catch (NoSuchFieldException e) {
        // maybe log that something bad happened?
    }
    if (multipartFileField != null) {
        Extensions annotation = multipartFileField.getAnnotation(Extensions.class);
        ACCEPTED_IMAGE_FORMATS = annotation.imageFormats();
        ACCEPTED_VIDEO_FORMATS = annotation.videoFormats();
    } else {
        ACCEPTED_IMAGE_FORMATS = new String[]{};
        ACCEPTED_VIDEO_FORMATS = new String[]{};
    }
}

Here, I don't need to ask what might throw the NoSuchFieldException,
it's obvious, which is good.

As for avoiding the static initializer...
if you want to have static fields with non-trivial constants,
then there's just no other way,
you have no choice but to initialize them in a static initialization block like this.
Other option would be to give up the static fields,
make them non-static and initialize in the constructor.
But this probably won't make much sense,
since the field values come from static data (MultipartFileWrapper.class).


Code structure for a login modal dialog.

First off, I'd retrieve all the elements right away, instead of running $(...) again and again:

var loginDialog = (function($) {
  var dialog, form, button, template;

  // Get the elements once, on page load
  $(function () {
    dialog = $("#login-dialog");
    form   = dialog.find("form");
    button = dialog.find(".btn-primary");
    template = $("#alert-tmpl");
  });

  function show() {
    dialog.modal({
      backdrop: "static",
      keyboard: false
    });
  }

  // ... et cetera ...

})(jQuery);

As you can see, I've also put the variable declaration first. If you use expressive functions, you should do the same with all those variables too (which is why I usually prefer to use standard function declarations instead - fewer variables to declare).

(oh, and, yes, I've moved the braces around, but we've covered that in the comments :)

Generally, though, it seems quite fine, and well-structured. There are some functions that could be dropped, since they just call a different function - for instance handleSuccess which is basically an alias for hide. On the other hand it's nicely descriptive to have a handleSuccess function. And if you want to more on success than simply call hide, it's of course nice to have encapsulated.

Lastly, in handleError you .append the error message to the form, so if there are more errors the form will keep growing. Don't know if that's by design, but I imagine you might want to only show one error at a time (and perhaps even remove it on success).


Object wrapper/parameter injection module

Looks quite good.
Nevertheless here are some thoughts:

Parameter Names

You might get problems when calling utils.parameterNames without arguments. E.g. func.toString() would fail if func is undefined.
Moreover you'll get an array with one entry  (['']) if you pass a function with no arguments (utils.parameterNames(->)) where you might expect an empty array.
You could change your implementation to this:

utils.parameterNames = (func=->) ->
  funcArgs = func.toString().split('(')[1].split(')')[0].split(',')
  (t for k in funcArgs when (t=k.trim()) isnt '')

Here is an other implementation (source) using an regular expression

getArgumentNames = (fn=->) ->
  args = fn.toString().match ///
    function # start with 'function'
    [^(]* # any character but not '('
    \( # open bracket = '(' character
    ([^)]*) # any character but not ')'
    \) # close bracket = ')' character
  ///
return [] if not args? or (args.length < 2)
args = args[1]
args = args.split /\s*,\s*/
(a for a in args when a.trim() isnt '')

We could also write s.th. like this:

fnRgx = ///
  function # start with 'function'
  [^(]* # any character but not '('
  \( # open bracket = '(' character
  ([^)]*) # any character but not ')'
  \) # close bracket = ')' character
///

argRgx = /([^\s,]+)/g

parameterNames = (fn) ->
  (fn?.toString().match(fnRegex)?[1] or '').match(argRgx) or []

The performance depend on the browser but the last one seems to be pretty fast (see benchmarks)

Expressions

In CoffeeScript every thing is an expression so you can turn this

if module
  _ = require('underscore');
else
  _ = window._

into this

_ = if module then require('underscore') else window._

Iteration

This:

for position, name of signature
  parameters[position] = context[name] if context[name]?

could also be written in that way:

for position, name of signature when context[name]?
  parameters[position] = context[name]

or even:

parameters[position] = context[name] for position, name of signature when context[name]?

It compiles all to the same JS. I'd prefer the second variant.


The only thing that I can see at first glance to show what the business rule is, is to do something like this

m_GlobalCode = "ABC"
result = GetEquivalentCode
Debug.Assert result = "ABC2013"

probably at the beginning.

I think this is exactly what the business rule is saying from my understanding of the information that you have given

you probably want to add something like this to follow it, just to be clear what the rule is.

m_GlobalCode = "AB"
result = GetEquivalentCode
Debug.Assert result = "AB"

These two pieces coupled together show the entire Business Rule.

  if the input string starts with "ABC" then return "ABC2013" otherwise return the input

6 tests should clearly define the Business Rule

Input: "ABC"
Input: "AB"
Input: vbNullString
Input: {Random String not Starting with "ABC"}
Input: "DABC"  Result: "DABC"
Input: "ABC5029DDD"

Number 5 shows that ABC must be at the beginning of the string

Numbers 1 & 6 shows what the Function is doing.

Numbers 2,3,4, & 5 show what happens when the ABC is not at the beginning


except Exception as e:
    raise e

First, you could simplify this to

except Exception:
    raise

Second, since you only re-raise it, you are not prepared to handle any Exception that could appear either with your code or the code managing the connection returned by your context manager. Thus you don't need that except clause.

Now the only thing left to manage is the state of the connection. Since there is no exception handling performed by your code, you are free to create the connection out of the try … finally and use that mechanism to only close the connection whatever happened:

@contextmanager
def smtp_connection(host, user=None, passwd=None, timeout=5):
    conn = SMTP(host=host, timeout=timeout)
    try:
        conn.ehlo_or_helo_if_needed()
        if user and passwd:
            conn.login(user=user, password=passwd)
        logger.debug('SMTP connected')
        yield conn
    finally:
        conn.quit()

You could also simplify the design by separating concerns. As it stand, your function does two things:

manage the connection;
perform some initial setup.

By delegating to a second context manager, you could separate these two behaviors into reusable bits:

@contextmanager
def smtp_connection(host, timeout):
    connection = SMTP(host=host, timeout=timeout)
    try:
        yield connection
    finally:
        connection.quit()

@contextmanager
def smtp_setup(host, user=None, passwd=None, timeout=5):
    with smtp_connection(host, timeout) as conn:
        conn.ehlo_or_helo_if_needed()
        if user and passwd:
            conn.login(user=user, password=passwd)
        logger.debug('SMTP connected')
        yield conn

But, looking at the second context manager, there is nothing to manage anymore since there is no teardown/cleanup anymore. Thus it is best to provide it as an independant function:

@contextmanager
def smtp_connection(host, timeout=5):
    connection = SMTP(host=host, timeout=timeout)
    try:
        yield connection
    finally:
        connection.quit()

def smtp_setup(conn, user=None, passwd=None):
    conn.ehlo_or_helo_if_needed()
    if user and passwd:
        conn.login(user=user, password=passwd)
    logger.debug('SMTP connected')

You would then need to change your calling code from

with smtp_connection(h, u, p, t) as conn:
    # do stuff

to

with smtp_connection(h, t) as conn:
    smtp_setup(conn, u, p)
    # do stuff

In the end, I personally don't like to have to manage the try ... finally inside the context manager. I don't find that natural as I preffer to write an explicit class using __enter__ and __exit__:

class smtp_connection:
    def __init__(self, host, timeout):
        self.smtp = SMTP(host=host, timeout=timeout)
    def __enter__(self):
        return self.smtp
    def __exit__(self, exc_type, exc_value, exc_trace):
        self.smtp.quit()

Using a class could also let you wrap this thing around SMTP directly:

class smtp_connection(SMTP):
    def __init__(self, host, timeout):
        super().__init__(host=host, timeout=timeout)
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, exc_trace):
        self.quit()
    def setup(self, user=None, password=None):
        self.ehlo_or_helo_if_needed()
        if user and passwd:
            self.login(user=user, password=passwd)
        logger.debug('SMTP connected')

Use it like:

with smtp_connection(h, t) as conn:
    conn.setup(u, p)
    # do stuff


It's ok for a first iteration.

But your 2nd iteration should be drawRectangle(int width, int height). That will force you to not hard-code your numbers.
Your 3rd iteration should be noticing that your rectangle only has 2 different rows (one row fills up the width with * and the other only has * in the beginning and end).  You might want to make a method drawHorizontal to draw the top and bottom and drawEnds to draw the sides.  For example

    void drawHorizontal(int width) {
      for (int i=0 ; i<width ; i++) {
         System.out.print("*");   /* notice I'm using print() not println() */
      }
      System.out.println("");     /* notice I'm using println() */
    }

    void drawEnds(int width) {
      System.out.print("*");
      for (int i=1 ; i<width-1 ; i++) {
         System.out.print(" ");
      }
      System.out.println("*");
    }


Map Character to Characters Most Frequently Found With it (in list of strings)

Here are some tips to keep in mind when writing code that needs to be optimal:

The single biggest thing is: reduce the time complexity! This is by far the most significant improvement you can possibly make. Avoid iterations over the data as much as possible. For instance, every time you check if the char was added to charMap, the containsKey() function iterates over data in the Map. There aren't many letters so you can have a small data structure where the position of the data (index) indicates what character it relates to, this will remove the need to iterate to search for a specific character. In other cases you may reduce the number of iterations by sorting your data and using an efficient search algorithm such as binary search.
Arrays are the fastest data structure, use them instead of more complex data structures wherever it makes sense to do so.
Minimize the amount of data to be stored/manipulated - this can too be achieved by position-coding the data in your data structure, the position where the numbers are saved tells you what character these numbers relate to, so there are no actual Character variables being created until you need to create them, and then you can write code that will create only the chars you need to use/output.

Here is my implementation of the function you were tasked to write, I also avoided some of the logic checks you did, but getting rid of a few if statements is not a significant optimization so don't worry about it, focus on the main points I explained and see how they are implemented.

(notice the difference caused by improving the time complexity: according to my benchmarking, my implementation works about as fast as yours (1.1 times faster) with an input of 3 strings in the list, but it works ~5.4 times faster than yours when given an input list of 30 strings, the speed gap grows the bigger the input gets)

public static Map<Character, List<Character>> companionChars(List<String> strings){
    Map<Character, List<Character>> result = new HashMap<>(27, 1);
    int[] lengths = {26, 26};
    int[][] companionCounts = (int[][]) Array.newInstance(int.class, lengths);

    for(String str : strings){
        int[] charsFound = new int[26];
        for(int x = 0; x < str.length(); x++)
            charsFound[str.charAt(x) - 'a'] = 1;
        for(int x = 0; x < 26; x++)
            if(charsFound[x] == 1){
                for(int y = 0; y < 26; y++)
                    companionCounts[x][y] += charsFound[y];
                companionCounts[x][x]--;
            }
    }

    for(int x = 0; x < 26; x++){
        ArrayList<Character> chars = new ArrayList<Character>();
        int max = 1;
        for(int y = 0; y < 26; y++){
            if(companionCounts[x][y] > max){
                max = companionCounts[x][y];
                chars.clear();
                chars.add((char)('a' + y));
            }
            else if(companionCounts[x][y] == max)
                chars.add((char)('a' + y));
        }
        if(!chars.isEmpty())
            result.put(new Character((char)('a' + x)), chars);
    }
    return result;
}

Main function:

public static void main(String args[]) {
    List<String> strings = Arrays.asList("aabc", "bcdddd", "cde");
    System.out.println(companionChars(strings));
}


Random distributions in Go with inheritance

Style comments

Don't panic. Return the incorrect value of n in your error using fmt.Errorf.
Use gofmt on your code. (Have your favorite editor call it on-save.)
There is no better way to convert a bool to an int than what you have.
Replace var u = … by u := ….
No need to use named returned parameters in Rn.

On your main question

What you have works, but consider if one caller of your library does:

cont := Continuous{}
cont.Rn(42)

If you can't guess, try it; it's a good way to learn =) Anyway, you don't want that to happen. So you can do this several ways. Before I'm going into two idiomatic options, let's talk about your interface definitions:

Rn only needs something that implements R, so you could probably have an interface only for this. Let's call this interface Law.
Your Continuouser should simply be called Continuous or ContinuousLaw (because it describes what a continuous law does). In its definition, replace the R() float64 by Law.
Your Continuous should be called MultiDrawer or something. The only reason you're defining it is because you want to draw multiple values; so name it accordingly.

Option 1:

func Rn(law Law, n int) []float64

It's very simple; what you're saying here is "give me a Law, I can give you n random values from it".

Option 2:

interface MultiDrawer {
    Rn(n int) []float64
}

struct multiDrawer { // unexported: you don't want callers to touch this directly
    Law
}

func NewMultiDrawer(law Law) MultiDrawer {
    return &multiDrawer(law)
}

func (md *multiDrawer) Rn(n int) []float64 {
    // your code using md.R()
}

You're saying something similar here: "give me a Law and I give you a MultiDrawer". It's better if you want to have a concept of a MultiDrawer variable that you'll later pass around or reuse.


Producing all allocations by n items from a list

(defun allocations (source length)
  (if (= 1 length)
      (list (list (car source)))
      (loop for processed = nil then (cons (car i) processed)
         for i on source
         for todo = (cdr i)
         appending
           (loop for intermediate
              in (allocations
                  (append (reverse processed) todo)
                  (1- length))
              appending
                (loop for prefix = nil then (cons (car suffix) prefix)
                   for suffix on intermediate
                   collect (append prefix (list (car i)) suffix))))))

This should be a more general case of the problem (i.e. it makes no assumption of the nature of the elements in the list), but it doesn't verify that there is enough of the elements in the source list to build the required number of permutations.


Testimonial section CSS inheritance and proper use of HTML5 elements

Everything looks clean. However, I found some things though:

font-size - Make the units consistent. You use px and em. I suggest you go em all the way.
background-size - Well, it exists for that reason, but it would be better if you actually sized the image in those dimensions rather than having them resized in CSS.
You "namespaced" everything by prefixing .testimonials. That's being a good developer. You're avoiding your styles from clobbering other elements. However, you forgot to do that for .author and p.


The order the method infos are returned in dose not appear to be a defined one, I would suggest filtering on argument types to avoid the risk of it all crumbling to dust when the order changes.

Also you may want to consider the case when a method is defined on both the base class and the subclass.

class A
{
    public static void DoAwsomeStuff()
    {
        // really awsome stuff.
    }
}

class B : A
{
    public static void DoAwsomeStuff()
    {
        // different but still awsome stuff.
    }
}

Hiding static methods like this should probably be frowned upon, but all the same I would suggest selecting the method with the most specific declaring type. Just to be safe.

MethodInfo method = null;

foreach(var current in methods)
{
    if(method == null || current.DeclaringType.IsAssignableFrom(method.DeclaringType))
    {
        method = current;
    }
}

Edit:

Another possibility worth exploring is the use of Type.InvokeMember(). This already takes the argument types and method hiding into account for you.

try
{
    result = _type.InvokeMember(
        binder.Name,
        BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod,
        null,
        null,
        args
        );

    return true;
}
catch(MissingMethodException)
{
    result = null;
    return false;
}


A quartic polynomial in four variables, for numerical integration

The compiler (when -fastmath or equivalent is active) will do a lot of optimizations for you, benchmark the current code and see if it's fast enough for your purposes. This means that the relative amount of time spent in that code is too small for speedups in that part to yield better results.

First step is to replace the pow calls with explicit (cached) multiplication. pow expects 2 floating point values and is a complex formula though it will most likely have a fast path for integer exponents (which after inlining will result in the same but I have little faith in compiler optimizations):

double calc_A(int i, const double *U) {
    double u0, u1, u2, u3;
    double res;
    u0 = U[i];
    u1 = U[i+1];
    u2 = U[i+2];
    u3 = U[i+3];

    double u0_2 = u0*u0;
    double u1_2 = u1*u1;
    double u1_3 = u1_2*u1;
    double u1_4 = u1_2*u1_2;
    //...
    res = 3 * u1_4 + 3 * u1_3*(u2 - 2 * u3) +
        u1_2*(3 * u2_2 - 7 * u2*u3 + 3 * u3_2) +
        u1*u2*(3 * u2_2 - 8 * u2*u3 + 4 * u3_2) +
        //...
}

Looking at the use case (calling it for every index in an array) it would pay to SIMD the function if your cpu supports double precision vector math (modern cpus almost certainly do).

This will mean using intrinsics for the math which will be less clear code but will probably be faster.


The right tool

As you've said, you are not using the right tool for this task : you can't parse HTML with regexps.

A better approach would be to use an already existing parser like BeautifulSoup.

A simpler container

At the moment, you are putting data in multiple lists to zip them all at the very end. It can be a very nice technique but in our case, you put in different containers things that actually belong together. Also, you have a risk of adding too many elements in a list and having information zipped with information that should be in a different row. An easier option is to have a single list where each elements contain everything you've parsed.

Also, you can take this chance to rewrite in a more straightforward way the parts where you add something a list and then refer to it with my_list[-1].

company_data = []

for i in range(len(table)):
    if bool(re.search(pattern = tick_ident_nasdaq, string = table[i])):
        exchange = "NASDAQ"
    elif bool(re.search(pattern = tick_ident_nyse, string = table[i])):
        exchange = "NYSE"
    else:
        exchange = None
    if exchange:
        ticker = re.search(pattern = name_grab, string = table[i]).group(1)
        name = re.search(pattern = name_grab, string = table[i + 1]).group(1)
        name = re.sub(pattern = "&amp;", repl = "&", string = name)
        cig = re.search(pattern = cigs_grab, string = table[i + 3]).group(1)
        cig = re.sub(pattern = "&amp;", repl = "&", string = cig)
        cig_sub = re.search(pattern = cigs_grab, string = table[i + 4]).group(1)
        cig_sub = re.sub(pattern = "&amp;", repl = "&", string = cig_sub)
        company_data.append((ticker, exchange, name, cig, cig_sub))

Compile your regexp

You can compile regexp if you plan to reuse them many times. It is more efficient and it makes it possible to use them like any Python object.

# Define regex used for parsing
tick_ident_nasdaq = re.compile('href=\"http:\/\/www\.nasdaq\.com\/symbol\/')
tick_ident_nyse = re.compile('href=\"https:\/\/www.nyse.com\/quote\/')
name_grab = re.compile('\">(.+)<\/a>	')
cigs_grab = re.compile('^(.+)	')
amp_re = re.compile("&amp;")

company_data = []

for i in range(len(table)):
    if bool(tick_ident_nasdaq.search(string = table[i])):
        exchange = "NASDAQ"
    elif bool(tick_ident_nyse.search(string = table[i])):
        exchange = "NYSE"
    else:
        exchange = None
    if exchange:
        ticker = name_grab.search(string = table[i]).group(1)
        name = name_grab.search(string = table[i + 1]).group(1)
        name = amp_re.sub(repl = "&", string = name)
        cig = cigs_grab.search(string = table[i + 3]).group(1)
        cig = amp_re.sub(repl = "&", string = cig)
        cig_sub = cigs_grab.search(string = table[i + 4]).group(1)
        cig_sub = amp_re.sub(repl = "&", string = cig_sub)
        company_data.append((ticker, exchange, name, cig, cig_sub))

"&" and "&"

What you are trying to do when substituing "&" with "&":

deserves to but put in a function on its own
actually corresponds to a common problem already solved : HTML entity decoding.


Django template block name changing function

This seems valid, and I don't think it should mess up Django's functionality.
Some improvements are possible.

This is not Pythonic:

if len(extend_nodes) == 0:
    return

Write like this:

if not extend_nodes:
    return

This is not Pythonic:

    if blocks.has_key(name):
        # ...

Write like this:

    if name in blocks:
        # ...

But...

You're not supposed to do this.
You haven't explained why you want to change template block names on the fly.
And I cannot think of a legitimate use case.
It's inefficient to do this operation on the fly,
for every page load.
What you should really do instead is update the template files in your project,
do the necessary renames once and save it,
so that you don't need this unnecessary extra operation.
The end result will be more efficient, and more robust.
Updating all files in your project is possible with a little scripting.


Creating a menu as nested unordered lists from JSON data

At the very least, you should clean up your variables:

htmlTxt is declared as var twice in the same scope.  I don't think you even need it at all.
cat is never used.
htmlStrTxt would be better as a local function within recurseMenu().  A shorter variable name would do just as well.
The level parameter is useless.

$(document).ready(function () {
        var url = "#";

        function recurseMenu(parent) {
            var s = '
';
            for (var x in menuItems) {
                if (menuItems[x].parentId == parent) {
                    s += '
' + menuItems[x].title + '';

                    if (menuItems[x].childCount > 0) {
                        s += recurseMenu(menuItems[x].id);
                    }
                    s += '
';
                }
            }
            return s + '
';
        }

        $("#listContainer").html(recurseMenu());
     });


Schema.org combining different categories

Home page

The Microdata is fine.

I don’t know if it’s possible with the design of your page, but typically you would link the name/logo (then you could omit the meta and you wouldn’t need alt content), so it could look like:

    Organizaton

short description on home page

Product page

You are using the name property (from TravelAgency) on a meta element, but do you really have no visible name of the travel agency on your page (e.g., in the header)? If you have one, you could use that element instead of meta.
The itemOffered property expects a Product item as value, but you are using text.

As you are already using Product → offers → Offer, there is no need for the reverse relation Offer → itemOffered → Product.

You probably want to use the name property instead, however, if the Product has the same name as the Offer, omit this property altogether.
If the only data about the Product is the name, consider omitting this item. You could use Offer directly (unless you have several offers for the same Product).
There is a superfluous .
Your span element has a content attribute, which is not allowed. Use a meta or data element (or in your specific case, just the content of the span.)


Sock merchant from hackerrank - idiomatic typescript?

Let's make it pure function:

function readLine() {
    return inputString[currentLine++];
}

IMHO both for loop should be transform to reduce, or at least the second one where you use only addition, it would be still simple and readable as a reduce().

Personally, I don't like those shorts like ws - sounds like websocket, ar and means nothing, obj and count are too generic.

result could be declared as const, as well obj and count.

And lastly, too much links as comments, why do you assume reviewer don't know TS, JS... or google? :)
Not to mention, the links could be dead soon.


Your code looks pretty good, but there is a no-no:

def checksum_one
  digit = sum_at(10)
  digit = calculate(digit)
  digit = 0 if digit > 9
  digit
end

Note thatdigit my have up to three different values in just four lines of code. This makes the code harder to follow. As a rule of thumb, use different variable names. That's how I'd write it:

def checksum_one
  digit = calculate(sum_at(10))
  digit > 9 ? 0 : digit
end


SQL Query to check if 100+ (or Dynamic) columns in table is null

Does this SQL code follow common best practices?

No.

SET @query = N'SELECT * FROM TableName WHERE COALESCE('+ @query +') IS NULL';

1) It is common best practice to not use 'Select *' in production code. One's apologetics might include 'Well, this is dynamic code ...' and if you're okay with that (or the customer is) then carry on.

2) I would use a Socratic method and ask what is the purpose of returning columns you know are null? Why wouldn't you write the query to only return the PK if all other columns are null?

  How is the quality of this code?

It looks is fine.

I would suggest if you want a better evaluation, to provide sample objects / DDL to allow others to run it locally. Perhaps to evaluate the query plan.


Being myself new to rust, take the following with a grain of salt. I would welcome further edits.

I think, generally, that there are two things your code is trying to do.
On one hand, it's about string tokens and concatenation.
On the other, there's the solving the 99 bottles problem.

99 Bottles

For this problem, your approach seems complex and results in rather gauche
code. What makes it so, is that it's hard to understand at first glance what
phrase is at any point.
Adding comments would be a good thing.
Myself, I would forego the whole tokenisation part, and solve it in a more
concise way.

There are only a handful of sentences in the song, which need slight variations.
I'd like to use something like Python's raw strings:

SOLO = r"{QTY} bottles of beer on the wall, {QTY} bottles of beer."
SOLOT.format(QTY=count)

In rust, I managed to get this behaviour by using std::String::replace:

const SOLO: &str = "{QTY} bottles of beer on the wall, {QTY} bottles of beer."
let mut solo: String = SOLO.to_string().replace("{QTY}", &count.to_string());

Once can likewise replace bottles for its singular form, one for it.

Other details to clarify are:
1. are negative bottles allowed?
2. in one place, we're talking of phrase, in another of verse, and returned are
a bunch of sentences. Which nomenclature is correct? A single term ought to be used.
3. We're only dealing with beer, perhaps bottles_of_beer could become bottles?

We then end up with something like so:

const SOLO: &str = "{QTY} bottles on the wall. ";
const CHORUS: &str = "Take one down and pass it around, {QTY} bottles of beer on the wall.\n";
const BOTTLE: &str = "bottle"; // for substitution when 1 bottle left.
const NONE: &str = "\
No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, {QTY} bottles of beer on the wall.\n\
";

pub fn get_song(start: u32, stop: u32) -> String {
    let mut song: String = String::new();

    for x in (start..stop+1).rev() {
        if x == 0 {
            let no_beer: String = NONE.to_string().replace("{QTY}", &start.to_string());
            song = song + &no_beer;
            break;
        }
        let mut solo: String = SOLO.to_string().replace("{QTY}", &x.to_string());
        let mut chorus: String = CHORUS.to_string().replace("{QTY}", &x.to_string());
        if x == 1 {
            solo = solo.replace("bottles", BOTTLE);
            chorus = chorus.replace("bottles", BOTTLE);
            chorus = chorus.replace("one", "it");
        }
        song = song + &solo + &chorus;
    }
    return song;
}

fn main() {
   println!("{}", get_song(10, 0));
}

note that I am not sure this is a correct way to do such constant
strings.
I think let mut song: String = String::new(); is the preferred style,
as seen in the rust book, over
let mut phrase: String;

The while loop can be replaced by a for loop. This is actually the textbook example:

for x in (stop..start+1).rev() {
    ...
}

There's the +1 increment to include the starting value, then the iterator is reversed to go from high to low values.

String Tokens and Concatenation

To stay on the string concatenation path, I suggest commenting what each path does.
There are several if n < 1, which could be put together.  Within that, n
is redefined and subtracted, leading to an nested if n < 1 test.

We can observe that there are two types of operations: building different types of sentences,
and checking whether we're at the end of the song (n < 1).

Let's agree to not return a phrase, but a paragraph:

let mut paragraph: String = String::new();

// Build qty of bottles on the wall sentence
if n < 1 {
  ...
  paragraph = format!(...);
} else { ... }

// Build qty of bottles left on the wall sentence
if n < 1 {
   paragraph = format!("{} {}", paragraph, ...);
} else { ... }

And so on.

Now I'm thinking, what's actually done here, is not checking a condition, but
rather matching a parameter, so if-elses could become:

// Build qty of bottles on the wall sentence
match n {
   0 => paragraph = format!("{}{}{}{}", N_UP, O_MORE, SPACE, bottles),
   _ => paragraph = format!("{}{}{}", n_str, SPACE, bottles),
}

By using match extensively, we also can remove the nested if-else:

    // Build closing
    let phrase = match n {
        0 => format!("{}{}{}", NINE_NINE, SPACE, bottles),
        1 => format!("{}{}{}{}", N_DOWN, O_MORE, SPACE, bottles),
        _ => format!("{}{}{}", qty, SPACE, bottles),
    };

Finally, we get to such a result:

const BOTTLE: &str = "bottle";
const BOTTLES: &str = "bottles";
const OF_BEER: &str = "of beer";
const UPPERCASE_N: &str = "N";
const LOWERCASE_N: &str = "n";
const O_MORE: &str = "o more";
const ON_THE_WALL: &str = "on the wall";
const SPACE: &str = " ";
const COMMA: &str = ",";
const PERIOD: &str = ".";
const NL: &str = "\n";
const TAKE: &str = "Take";
const IT: &str = "it";
const ONE: &str = "one";
const DOWN_AND_PASS: &str = "down and pass it around";
const GO_STORE: &str = "Go to the store and buy some more";
const NINE_NINE: &str = "99";

pub fn verse(n: u32) -> String {
    let mut paragraph: String = String::new();

    // Is `bottle` plural in this paragraph?
    let bottles: String = match n {
        1 => BOTTLE.to_string(),
        _ => BOTTLES.to_string(),
    };

    // Create first half of first verse.
    let phrase: String = match n {
        0 => UPPERCASE_N.to_owned() + O_MORE + SPACE + &bottles,
        _ => n.to_string() + SPACE + &bottles,
    };
    paragraph = paragraph + &phrase;
    paragraph = paragraph + SPACE + ON_THE_WALL + COMMA + SPACE;

    // Create second half of first verse.
    let phrase: String = match n {
        0 => LOWERCASE_N.to_owned() + O_MORE,
        _ => n.to_string(),
    };
    paragraph = paragraph + &phrase;
    paragraph = paragraph + SPACE + &bottles + PERIOD + NL;

    // Create first half of second verse.
    let phrase: String = match n {
        0 => GO_STORE.to_string(),
        1 => TAKE.to_owned() + SPACE + IT + SPACE + DOWN_AND_PASS,
        _ => TAKE.to_owned() + SPACE + ONE + SPACE + DOWN_AND_PASS,
    };
    paragraph = paragraph + &phrase;
    // Add punctuation
    paragraph = paragraph + COMMA + SPACE;

    // Create second half of second verse.
    let phrase = match n {
        0 => NINE_NINE.to_owned() + SPACE + &bottles,
        1 => LOWERCASE_N.to_owned() + O_MORE + SPACE + BOTTLES,
        _ => n.to_string() + SPACE + &bottles,
    };
    paragraph = paragraph + &phrase;

    // Finish second verse
    paragraph = paragraph + SPACE + OF_BEER + SPACE + ON_THE_WALL + PERIOD + NL;

    return paragraph;
}

fn main() {
    let start: u32 = 10;
    let stop: u32 = 0;
    let mut song: String = String::new();
    for x in (stop..start+1).rev() {
        song = song + &verse(x);
    }
    println!("{}", song);
}

This is still not too clear code to me, and I'd rather work with the
first variant.

On a final note, there were places were you use n_str or format!("{}", n), be mindful of this types of errors.
Likewise, typically start/stop or begin/end are used, but try not to mix them up.
Lastly, I had a lot of trouble distinguishing between O_DOWN N_DOWN, N_UP.


This code is wrong in a great many ways.

public int BinarySearchIterative(int[]inputArray, int Key) {

The name describes how the code is implemented, not what it does. The caller doesn't care how your search is implemented. The caller cares about what the contract of the method is: what goes in, what comes out, and what the relationship between those two things is.

Non-standard spacing.

Formals should start with a lower-cased letter.

Why an array?  What if we want to binary search a list?  Why ints?  What if we want to binary search an array of doubles?  This signature is needlessly specific.

Why return int?  What if the value is not found; what value will you return then?  Are you returning the value, or the index?  This is nowhere clear in the signature, and therefore it needs a comment.

    int min = 0;

What is the purpose of this assignment to a variable that is only read once?  You could say const int min = 0; or simply pass zero. Or not pass it at all; if you always pass zero then the callee doesn't need to have it passed, does it?

    Array.Sort(inputArray);

Someone handed you an array and you sorted it for them. What if it was already in an order they liked? You just wrecked their order. That's rude.  What if it was already sorted? Then you just spent time sorting an array that was already sorted.

Consider what the contract of this method should be; should it be that the array is already sorted?

    int max = inputArray.Length;

The code crashes if the input array is null.  You should detect that situation early and throw an invalid argument exception.

Again giving a name to a value that you only use once. Seems unnecessary.

    return BinarySearchIterative(inputArray,Key,min,max,0);

Non-standard spacing.

Why do min and max get names but whatever that zero is does not?

public int BinarySearchIterative(int[] inputArray, int key, int min, int max,int LoopCount) {

Why is this public? It appears to be a private implementation detail of the other method.

Again with the bad signature.

And again with the nonstandard spacing choices.

    while(min <= max) {
        int mid = (min + max) / 2;

A problem that is in practice a non-problem, but still deserves to be called out.  If min + max is greater than int.MaxValue, this wraps around to a negative number, which you then divide by 2.

This is a non-problem in practice because in C# an array is pretty much never observed to have more than a billion items. But to signal to the reader that you have thought this sort of thing over, you might want to use a different expression that gives the midpoint without overflowing. Can you devise such an expression?

        if(key == inputArray[mid]) {
            return ++mid;

So there you are debugging your program and stepping through the code, and you're watching the value of mid and suddenly it changes.  By doing this you make the person doing the debugging -- you -- have to remember whether they're watching the original value or the new value.  Don't make yourself think.  Don't mutate variables unnecessarily.  Either return mid; or return mid + 1;, whichever one is correct. Don't mutate a variable you're never going to read again in order to save a couple of keystrokes.

        } else if(key < inputArray[mid]) {
            max = mid - 1;

Again, mutating your formals is a bad practice that makes it hard to debug your program. Don't do it.

        } else {
            min = mid + 1;
        }
        LoopCount++;
    }
    return LoopCount;
}

What the heck is "loopcount"?

Why is it capitalized?

Why is this the return value of the method?

What connection does it have with the problem of binary searching?

Suppose the search fails after ten loops. So you return 10.  Now suppose the search succeeds and finds the element 10 is the key, so you return 10. How does the caller know whether the search succeeded or not?

Why is the count passed in at all, if you're always going to pass zero? If you want to count loops then make a local variable.

For that matter, why do you pass in min, max, etc, if you could simply compute them?  Why do you have two methods, one of which just calls the other, passing things that the inner method could have computed itself?

Start over.

Start with a clear statement of the problem.

My method takes as it argument an IList<int> and a target int. The list must be sorted and non-null. It returns null if the target is not in the list; it returns the index of the target if it is in the list.

Now that you have a statement of the problem, write the signature:

public static int? SearchSortedList(IList<int> list, int target)

Now you have everything you need right in this method already to implement binary search, so take it from here. There's no need for an auxiliary method, and there's no need for a loop count. Can you write the body of this method correctly?


CultureInfo with fallback routing to another language

Bugs

So, some interesting bugs. If I specify two cultures that have the same invariant, but are different versions it creates really unpleasant circumstances. (Infinite loops, anyone?)

var cultureInfo2 = FallbackCultureInfo.Build("en-GB", "en-US", "fr-CH");

That creates an infinite loop when rooting through the parent.
 So does:

var cultureInfo2 = FallbackCultureInfo.Build("en-GB", "fr-CH", "fr-FR", "de-CH");

Why does this matter? I could see a very real use case being:

cultureInfo = FallbackCultureInfo.Build("en-AU", "en-GB", "en-US");

(Use the Australian English culture, if you can't find it there use Great Britain English culture, if you can't find it there use the United States English culture.) Though, using the neutral (en) as the second in line may very well solve that problem with most strings, but it's still a possibility that this chain could be used and is now broken.

Of course, it's not consistent because of your static member there.

var cultureInfo = new System.Globalization.CultureInfo("en-GB");
cultureInfo = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");
cultureInfo = FallbackCultureInfo.Build("en-GB", "fr-FR", "de-CH");

When looking through all the parents of that second culture set, I don't get the correct tree.

en-GB
en
fr-CH
fr
de-CH
de

But I specified fr-FR for the second fallback!?!?!?!

Of course, we can get even more interesting results with a few other options:

cultureInfo = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");
cultureInfo = FallbackCultureInfo.Build("fr-CH", "it-CH", "de-CH");

fr-CH
fr
de-CH
de

Wait, what? Where did it-CH go?

cultureInfo = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");
cultureInfo = FallbackCultureInfo.Build("fr-CH");

fr-CH
fr
de-CH
de

Ah, I guess I really did need de-CH after all.

While both of these bugs are pretty major, for your situation they're really not something you would look for. You are specifically switching between languages that have different parents, and you're only creating one FallbackCultureInfo. (Which is probably the most likely scenario.)

Review

In C# we prefer the string alias instead of the String type.

Other than that, I have no real issues with the structure of your code, but I do have an issue with how you solved the problem.

Alternate Implementation

From what understand of the documentation, you should be able to get away with making this a lot simpler:

  The cultures have a hierarchy in which the parent of a specific culture is a neutral culture, the parent of a neutral culture is the InvariantCulture, and the parent of the InvariantCulture is the invariant culture itself. The parent culture encompasses only the set of information that is common among its children.

  If the resources for the specific culture are not available in the system, the resources for the neutral culture are used. If the resources for the neutral culture are not available, the resources embedded in the main assembly are used. For more information on the resource fallback process, see Packaging and Deploying Resources in Desktop Apps.

Basically, you should be able to just work with the Parent property and build from there.

public class NewFallbackCultureInfo : CultureInfo
{
    public NewFallbackCultureInfo FallbackCulture { get; }

    public NewFallbackCultureInfo(string name, params string[] names)
        : base(name)
    {
        if (names.Length > 0)
        {
            FallbackCulture = new NewFallbackCultureInfo(this, names);
        }
    }

    private NewFallbackCultureInfo(CultureInfo sourceCulture, params string[] names)
        : base(sourceCulture.Parent.Name)
    {
        var newNames = new string[names.Length - 1];

        for (int i = 1; i < names.Length; i++)
        {
            newNames[i - 1] = names[i];
        }

        FallbackCulture = new NewFallbackCultureInfo(names[0], newNames);
    }

    public override CultureInfo Parent => FallbackCulture ?? base.Parent;
}

Note that we also built this without the .Build pattern, and relied instead on constructors. It's more natural this way, and preserves the original CultureInfo usage.

The only downside I see is that the original parent chain may not be preserved, if it goes more than one level.

We can fix that by modifying our private constructor:

private NewFallbackCultureInfo(CultureInfo sourceCulture, params string[] names)
    : base(sourceCulture.Parent.Name)
{
    if (string.IsNullOrEmpty(base.Parent.Name))
    {
        var newNames = new string[names.Length - 1];

        for (int i = 1; i < names.Length; i++)
        {
            newNames[i - 1] = names[i];
        }

        FallbackCulture = new NewFallbackCultureInfo(names[0], newNames);
    }
    else
    {
        FallbackCulture = new NewFallbackCultureInfo(this, names);
    }
}

When tracing the Parent chain, I found that the chain produced by my version is identical to the chain produced by your version, except it doesn't break when tested against the criteria that broke your version.

I apologize if this felt brutal, but I was actually having a bit of fun with it after I realized what was happening.


What's the problem with your implementation? You clear the tree and add new (filtered) nodes. Somehow, TreeView1.Nodes.Clear(); is under comment, so it may be supposed that you want to preserve full node structure. If so, just store it in memory:

var query = FindNodeByValue(PersistentNodeSet.Nodes, fieldFilterTxtBx.Text);
if (query != null)
{
    TreeView1.Nodes.Clear();
    foreach (TreeNode node in query.ToList())
        TreeView1.Nodes.Add(node);
    TreeView1.ExpandAll();
}

And if you want the tree to preserve original structure, you need to use recursion in FindNodeByValue().


General stuff

#includes are missing
missing using namespace std; (which by itself is discouraged, especially in header files).
Graph::cycles path result contains not only the cycle, but alse the vertices that led there (e.g. in A -> B -> C -> B, A would be included in path though it is not part of the cycle). This might or might not be intended.
Inconsistency: Graph::cycleHelper takes visited as bool[], but recStack as bool *, even though the usage for both is the same.
if(visited[v] == false) can easily be rewritten to if(!visited[v])
Graph::cycle treats path as if it has full control over all elements already present. This behavior might be unexpected by users of the class and should at the very least be thouroughly documented.

Memory management

Graph::cycle leaks both visited and recStack.
Graph::addEdge never checks whether its parameters are in the valid range. If they aren't, there might be accesses to out-of-bounds memory.

These issues can be fixed by using appropriate data structures and error checking. Generally, prefer using RAII constructs (like std::unique_ptr or containers) for resource acquisition.

Data structures

Prefer std::array (if size is statically known) or std::vector (if not) over raw arrays. This also helps with memory cleanup.
Try to structure similarly used variables in their own class or struct.
Prefer std::vector (preferred) or std::deque (if constant time frontal insertion/removal is needed) over std::list, unless you absolutely need constant time random insertion/removal (and even then, you might want to measure std::vector as it is surprisingly efficient on modern hardware).

Class design

Some variables have very cryptic names and few (if any) documentation to their meaning.

Graph::V: Represents the number of vertices in the graph. Maybe rename to vertex_count or num_vertices or similar.
u and w in Graph::addEdge: There is not way to infer whether the edge is added from u to w or vice versa. Maybe rename to something like from and to?
Graph::cycle: cycle is an unfornate choice of name, as the verb cycle has a different meaning. hasCycle or findCycle better express the intention behind this member function.

There is an implicit assumption that "vertex index" == "vertex value". If there ever is a case where this assumption does not hold, the whole class will have to be redesigned.
Graph::cycle violates the Single Responsibility Principle (SRP). It does two things ("check whether there is a cycle" and "return the cycle"), which might benefit users of the class that want both operations, but hinders other users that only want one of the operations.
Graph is built upon the assumption that no more vertices will be added after construction. While this might be true in your specific use case, this won't be true in general.
A specific edge might be added multiple times, which might increase worst case runtimes (as iteration of the edges of a vertex can become greater than \$\mathcal{O}(n)\$

Amending all the points

If I had to implement this, the result would look like this:

#include <vector>
#include <algorithm>
#include <stdexcept>
#include <deque>

class graph {
    using node_type = int;

    class vertex {
        node_type value;
        std::vector<vertex *> edges;
        bool visited = false;
        bool marked = false;

    public:
        vertex(node_type name) : value{name}, edges{} {}

        node_type name() const { return value; }
        bool is_marked() const { return marked; }
        void clear_flags() { visited = false; marked = false; }

        bool has_edge(vertex *to) const {
            return std::find(std::begin(edges), std::end(edges), to) != std::end(edges);
        }
        void add_edge(vertex *to) {
            if(!has_edge(to)) edges.push_back(to);
        }

        vertex *find_first_marked_edge() {
            auto match = std::find_if(std::begin(edges), std::end(edges), [](auto& edge){ return edge->marked; });
            if(match == std::end(edges)) return nullptr;

            return *match;
        }

        bool is_part_of_cycle() {
            if(marked) return true;
            if(visited) return false;

            visited = true;
            marked = true;

            for(auto& edge : edges) {
                if(edge->is_part_of_cycle()) return true;
            }

            marked = false;
            return false;
        }
    };

    std::vector<vertex> vertices;

public:
    graph() = default;
    graph(std::initializer_list<node_type> init) : vertices{} {
        for(auto& name : init) {
            add_vertex(name);
        }
    }

    void add_vertex(const node_type& name) {
        if(std::find_if(std::begin(vertices), std::end(vertices), [&](auto& vert){ return vert.name() == name; }) != std::end(vertices)) {
            throw std::invalid_argument{"a vertex with this name already exists"};
        }
        vertices.emplace_back(name);
    }

    void add_edge(node_type from, node_type to) {
        auto& from_vert = find_vertex(from);
        auto& to_vert = find_vertex(to);

        from_vert.add_edge(&to_vert);
    }

    bool has_cycle() {
        for(auto& vert : vertices) {
            vert.clear_flags();
        }

        for(auto& vert : vertices) {
            if(vert.is_part_of_cycle()) return true;
        }

        return false;
    }

    std::deque<node_type> find_first_cycle() {
        auto cycle = std::deque<node_type>{};
        if(!has_cycle()) return cycle;

        auto cycle_iter = find_first_marked_vertex();

        while(std::find(std::begin(cycle), std::end(cycle), cycle_iter->name()) == std::end(cycle)) {
            cycle.push_back(cycle_iter->name());
            cycle_iter = cycle_iter->find_first_marked_edge();
        }

        while(cycle.front() != cycle_iter->name()) cycle.pop_front();

        return cycle;
    }

private:
    vertex& find_vertex(node_type name) {
        auto match = std::find_if(std::begin(vertices), std::end(vertices), [&](auto& vert){ return vert.name() == name; });
        if(match == std::end(vertices)) {
            throw std::invalid_argument{"vertex could not be found"};
        }

        return *match;
    }

    vertex* find_first_marked_vertex() {
        auto match = std::find_if(std::begin(vertices), std::end(vertices), [](auto& vert){ return vert.is_marked(); });
        if(match == std::end(vertices)) return nullptr;
        return &*match;
    }
};

Points to note:

graph::vertex encapsulates all information about a vertex. I changed recStack to marked, since many graph algorithms work with marked vertices.
No manual memory management (= no memory leaks). Everything is owned by containers.
I introduced some descriptive helper functions. This makes the code much more readable.
If the value of the vertices ever needs to be changed (or templated), only the definition of graph::node_type needs to be adjusted.
For a more deterministic performance, graph::vertex::edges could be kept sorted at all times.
Some functions have a first in their names, as there might be more results (in the general case).


Merge sort in one Single Function in Scala

Let me very clear here: I don't like what you have done and I don't like what you want to do.

With that out of the way, however, let me explain myself:

Scala is heavily inspired by the functional paradigm, which favors logic development by composition of smaller functions into larger ones and using a more declarative style, where you tell the computer "what" you want to do, not "how" you want to do it., unlike primarily imperative languages like C/C++/C#/Java.

Following the functional paradigm leads to more concise, verifiable and readable code (in most cases) over equivalent imperative implementations.

Pattern matching and recursion are especially important in the functional paradigm, where uncontrolled global mutable state is an anathema.

Yet, in Scala, you want to to do it the imperative way. Very well, Scala allows you to do it. However, should you? Most wouldn't think so.

Now on to the code review.

Observations

All you have done is hard-inlined the merge of mergeSort into the mergeSort() function itself.

If function call overheads are your primary concern for doing this, you probably shouldn't be using Scala. You should be using C/C++.

However, you're using Scala. So split it up. Write the merging function as a separate function, following the Single Responsibility Principle (SRP).

You have said that you don't want to pattern match and want to loop over the elements of the array, when you very well know merge sort in Scala can be implemented as a one-liner. That is kind of like taking the engine out of your car because you want to ride it like it's a quadricycle (or motorbike to bicycle, whichever makes more sense).

Horrible variable naming. aR1 and aR2 mean what, exactly? Why not leftSubArray and rightSubArray? More typing, yes, but that much clearer.

Suggestions

Write Scala like Scala should be written. You will be benefiting any other who will have to work on your code later. You will be benefiting yourself if you ever look at this code after you've gained more experience.
Use an IndexedSeq instead of an Array. Updates will not be in-place if you use the IndexedSeq object's apply() method (which returns a scala.Vector in Scala 2.11), as this is an immutable data structure unlike an Array. However, a Vector gets you type covariance. To get around the immutability in your design, keep the Vector as a var and reassign the result of any calls to updated() on it to itself. This is a first step on the path of functional-ness.
The Scala Predef and standard libraries have a lot of nice functions for you to exploit instead of explicitly looping over everything. You could try foreach, map and flatMap to help. There's also the handly sequence concatenation operator ++. There's also handy comparison functions like orderBy, and something which invalidates the need for what you are trying to do, sorted and sortBy
Try until instead of to for ranges. until will return a half-open interval in comparison to the closed interval returned by to. That is:

0 to 10 = [0,1,2,3,4,5,6,7,8,9,10]
0 until 10 = [0,1,2,3,4,5,6,7,8,9]

That should help get rid of some of the ugly -1s.
Even imperative merging isn't that complicated. Try the following, it should help:

def merge(arr: Array[Int], low: Int, mid: Int, high: Int): Array[Int] = {
    /*[low..mid..high), high is exclusive*/
    var (i, j, k) = (0, 0, 0)
    val (leftLength, rightLength) = (mid - low + 1, high - mid)
    /* create temp arrays */
    val (leftArr, rightArr) = Array(leftLength), Array(rightLength)
    /* Copy data to temp arrays leftArr and rightArr */
    arr.copyToArray(leftArr, low, leftLength)
    arr.copyToArray(rightArr, mid, rightLength)
    /* Merge the temp arrays back into arr(l..r)*/
    i = 0; // Initial index of first subarray
    j = 0; // Initial index of second subarray
    k = l; // Initial index of merged subarray
    while (i < leftLength && j < rightLength){
        if (leftArr(i) <= rightArr(j)){
            arr(k) = leftArr(i);
            i+=1;
        }
        else{
            arr(k) = rightArr(j);
            j+=1;
        }
        k+=1;
    }
    /* Copy the remaining elements of leftArr, if there
       are any */
    while (i < leftLength){
        arr(k) = leftArr(i);
        i+=1;
        k+=1;
    }
    /* Copy the remaining elements of rightArr, if there
       are any */
    while (j < rightLength){
        arr(k) = rightArr(j);
        j+=1;
        k+=1;
    }
    arr
}

I use Array instead of IndexedSeq in the above example as I need the intrinsic mutability of arrays in the presented method. It could have been written using IndexedSeq and assignment updates instead, but that would make the intent of the code a little less clear IMHO.

The functional one can be as simple as:

    def merge(left: IndexedSeq[Int], right: IndexedSeq[Int]): IndexedSeq[Int] =
        (left ++ right).sorted

The implementation without sorted() involves pattern matching, take a look here for details (especially @Shadowlands' answer for one without explicit pattern matching).

This was all assuming you've made merge a separate function. You don't need that many Boolean flags to maintain state if you do sequential merging. If you haven't split them up already, then do it now.
Splitting the array into parts can be handles by the splitAt(Int)function of Array, which takes as a parameter the index to split the array at, and returns a tuple containing the left and right parts. So, we could have the following:

 (leftArr, rightArr) = arr splitAt (arr.length / 2)

You sure you still don't want pattern matching?

Just to show off pattern matching, the canonical Scala solution (adapted to work on Seqs for Scala 2.10+, is the following:

    def mergeSort[T <: Ordered[T]](xs: Seq[T]): Seq[T] = {
      val n = xs.length / 2
      if (n == 0) xs
      else {
        def merge(xs: Seq[T], ys: Seq[T]): Seq[T] =
            (xs, ys) match {
            case(Nil, ys) => ys
            case(xs, Nil) => xs
            case(x :: xs1, y :: ys1) =>
              if (x < y) x::merge(xs1, ys)
              else y :: merge(xs, ys1)
        }
        val (left, right) = xs splitAt(n)
        merge(mergeSort(left), mergeSort(right))
      }
    }

Enriched with parameterized types (generics for a non-math guy)!

And for a code-golf answer, which doesn't really handle empty lists, see @lambruscoAcido's answer on PPCGSE.


Well, you should refactor your code so that you don't repeat yourself:

private async Task<List<ItemRetrieved>> GetValuesAsync(object parametersAsAnonymousObject)
{
    var requestUrl = MakeRequestUri("v3/get");

    var request = new HttpRequest(HttpMethod.Post, requestUrl);
    request.AddBody(parametersAsAnonymousObject);

    var response = await SendAsync<ItemRetrievedWrapper>(request);
    return response.List.Values.ToList();
}

public Task<List<ItemRetrieved>> GetAllUnreadAsync(int sinceInUnixTime = 0)
{
    return GetValuesAsync(new
        {
            consumer_key = _consumerKey,
            access_token = _accessToken,
            state = "unread",
            sort = "newest",
            since = sinceInUnixTime
        });
}

public Task<List<ItemRetrieved>> GetFavoriteAsync(int sinceInUnixTime = 0)
{
    return GetValuesAsync(new
        {
            consumer_key = _consumerKey,
            access_token = _accessToken,
            favorite = 1,
            sort = "newest",
            since = sinceInUnixTime
        });
}

This sill repeats consumer_key and access_token, but I think getting rid of that repetition would be too complicated, so it's not worth it (unless you have big number of these methods).


A few things I noticed when reading through (I don't know much about how Windows.h works, so I mostly focused on stuff not related to it)

This made me laugh:

// god help us

At the same time, though, it doesn't really describe what's happening. In this case, you don't really need an explanation; it's decently obvious what's up just by reading the relevant documentation. In other cases, though, you don't explain. For example...
here:

// parhaps I should use sprintf?

Why aren't you? I'm assuming the answer is "I couldn't see a clear benefit", but then explain that in a few words. (also, *perhaps)
wOld and wNew are bad variable names. Something like oldAttributes and newAttributes would be better, since it describes what's actually going on. If that's not what's going on, you should provide better variable names so I can understand what they should be :)
Why are you making j a WORD? strlen returns a size_t; while WORD is (usually, IIRC) 16 bits, size_t can be a great deal larger. Is it unlikely that you'll be encountering strings that are longer than 2^16 characters? Yes. Is the fix so easy to implement that there's no reason not to? Also yes.
Possible UB at switch(argv[2][j + 1]). If j == strlen(argv[2]), argv[2][j + 1] accesses memory outside of argv[2] (one past the end, in fact). Depending on how, specifically, the memory is laid out, this may not crash the program. It'd be better to do for (j = 1; j < len /* see below */; ++j) and use j - 1 and j where you use j and j + 1, respectively.
strlen operates by doing something roughly like this:

char *cur = your_string;
while (*cur) ++cur;
return cur - your_string;

That means that it's O(n). Performing that calculation makes your whole loop there O(n^2). If you store the length of argv[2], then compare to the stored length, you can improve the speed by a decent amount. Of course, for the number of characters you're most often dealing with, and with how simple your loop is, this doesn't matter so much, but it's a bad habit to get into.
Pretend it's six months later and you've been dealing exclusively not with text. When you see this:

argv[2][j]   = 0xa;
argv[2][j+1] = 0xd;

are you going to say "that's super clear and I know exactly what it does", or will you have to Google what the ASCII characters 0xa and 0xd are? You should put a comment there explaining it.
// How do I turn a char ** into a va_list ???

I don't think you can. Sorry.
In that same area, why are you assuming that accessing argv at argc and above will be valid, or that argv[2] will be a valid format string? You should check. Alternatively, just forget about building formatting in and let the calling code handle it (Bash, for example, can do that easily) -- it's a lot of work to try to do it yourself, for little to no benefit.
Your error codes are uninformative. Given that all you have is an integer, that's pretty much par for the course, but the least you could do is document them in the help message.
Related: Try running this simple C program from Bash:

int main() { return -1; }

Look at its return code -- it's 255, not -1. See here for more information; the gist of it is that negative numbers might not be interpreted that way by the OS. Stick to positive ones.
What's the point of this?

if(!v) { /* nop */ } // could not reset color...

The compiler just optimizes it out anyway; you might as well replace it with

// if it fails, we don't really care

to make it blatantly obvious that it doesn't matter.
feature-request Let me put in a color's name and see the output in that color, rather than making me use the number.

That's all I saw. Someone who's more familiar with the Windows API might find more.


Validation methods to ensure start and end date come after existing instances

Instead of trying to convert to int and catching TypeError,
it would be better to check for None values.

Instead of committee_set.aggregate(Max('start_year'))["start_year__max"],
you could give a custom alias to the max value,
making the code slightly more compact.

Instead of getting the latest start and end years in the beginning,
it would be better to delay getting the latest end year until it's needed.
That way you may be able to avoid one unnecessary query.

Instead of the style formatting strings with '%s' % (...),
the modern way is to use '{}'.format(...).

Combining the above tips, I would write the main part like this:

query = Committee.objects

latest_start_year = query.aggregate(max=Max('start_year'))['max']
if latest_start_year and int(self.start_year) <= int(latest_start_year):
    raise ValidationError("Start year {} must be greater than most recent {}".format(self.start_year, latest_start_year))

latest_end_year = query.aggregate(max=Max('end_year'))['max']
if latest_end_year and int(self.end_year) <= int(latest_end_year):
    raise ValidationError("End year {} must be greater than most recent {}".format(self.end_year, latest_end_year))

If it's not very important to include in the error message the latest start and end years,
a more compact and more efficient solution is possible:

query = Committee.objects

if query.filter(start_year__gt=self.start_year).exists():
    raise ValidationError("Start year must be greater than most recent")

if query.filter(end_year__gt=self.end_year).exists():
    raise ValidationError("End year must be greater than most recent")

And let's not forget about test cases.
Django provides a rich framework for testing.
Here are some examples:

class CommitteeTests(TestCase):
    def test_create_first(self):
        self.assertEqual(0, Committee.objects.count())
        Committee(start_year='1991', end_year='1992').save()
        self.assertEqual(1, Committee.objects.count())

    def test_create_second_valid(self):
        self.assertEqual(0, Committee.objects.count())

        Committee(start_year='1991', end_year='1995').save()
        self.assertEqual(1, Committee.objects.count())

        Committee(start_year='1992', end_year='1996').save()
        self.assertEqual(2, Committee.objects.count())

    def test_should_fail_if_start_is_before_latest_start(self):
        Committee(start_year='1991', end_year='1995').save()
        with self.assertRaises(ValidationError):
            Committee(start_year='1990', end_year='1995').save()

    def test_should_fail_if_end_is_before_latest_end(self):
        Committee(start_year='1991', end_year='1995').save()
        with self.assertRaises(ValidationError):
            Committee(start_year='1992', end_year='1994').save()

Lastly, you didn't mention about it,
but the current code allows Committee instances having start date after end date.
Probably it would be a good idea to prevent that too,
not to mention valid numeric values.
These validations should come first before the others querying the database,
and there should be test cases for them too.


A safer way to return a generic indicator object indicating failure

A fairly clean way is to use Optionals, like these or those. So you would make getNodeBefore return an Optional<Node<E>>.

The badNode idea is, hm, exotic to me.


You can convert it to two array. The first will normalize multiple "aliases" of the same key into one and second will have your address values.

var aliases = {
  "hyde" : "hydepark",
  "uofc" : "hydepark",
  "uchicago" : "hydepark",
  "wttw" : "willis"
};

var addresses = {
  "hydepark" : "5801 South Ellis Avenue, Chicago, IL",
  ...
};

var alias = aliases[xstreets[2]];
if(alias == undefined) {
  alias = xstreets[2]
}
var address = addresses[alias];
if(address == undefined) {
  return xstreets[0]+" & "+xstreets[1]+" Chicago IL";
}
return address;


Let's start with the zipcode data imported from the CSV file. This should probably be contained in its own method:

def get_zipcodes(zip_code_col_name, file_name="Downloads/test_order.csv"):
    excel_data = pd.read_csv(file_name, encoding='utf8')
    if zip_code_col_name not in excel_data.columns:
        raise ValueError("Missing zipcode column")
    return excel_data[zip_code_col_name].unique().tolist()

Note that pandas.Series objects have a unique method that avoids your expensive loop (the in lookup is \$\mathcal{O}(n)\$ for lists). If that was not the case you could have used set(excel_data[zip_code_col_name].tolist()), instead. The tolist is not strictly needed, since a pandas.Series is also iterable (and that is all you do with it).

Your main code should also be in a function (called main, if you can think of nothing else):

def main():
    # Putting max call to 49 for 1 hour
    get_geo_info_limited = RateLimiter(max_calls=49, period=3600, callback=limited)(get_geo_info)

    results = [get_geo_info_limited(zipcode, API_KEY, RETURN_FULL_RESULTS) for zipcode in zipcodes]
    df = pd.DataFrame(results)
    df.to_csv('Downloads/geo_info.csv', index=False)

Here I used the fact that RateLimiter can also be used as a decorator (which is usually done using the @RateLimiter syntax during function definition, but can also be done manually like here) and a list comprehension instead of a manual for loop.

You can then call this main function under a if __name__ == "__main__": guard to enable importing from this module from another script.


Looks like you over-thought it a little bit. Callbacks are indeed a powerful abstraction, but it looks overkill in this case. Some notes:

Use symbols to codify @facing: :east, :north, ...
a hint to write move without callbacks:

increments = {:north => [0, +1], :east => [+1, 0], :south => [0, -1], :west => [-1, 0]}

A hint to write left without callbacks:

new_facing = {:north => :west, :east => :north, :south => :east, :west => :south}

This way you describe what the robot does not with code (callbacks) but with data structures (which can be as simple as a hash).

As requested: the complete implementation of left:

def left
  new_facing = {:north => :west, :east => :north, :south => :east, :west => :south}
  @facing = new_facing[@facing]
end


Return the last word of the url and capitalize the first letter

Seems alright, though the names str and str1 aren't very descriptive names. Also, indentation is inconsistent.

I'd also point out that your code obviously isn't real code (which technically makes it off-topic for Code Review) due to the {{Click URL}}. I can still tell what's going on, but in the future, post the real code. Or at least post a working piece of code where the function takes a URL as its argument or something, rather than having a hard-coded syntax error!

But beyond that: URLs can be complex. While I'm sure this is built for a very specific purpose, and you're expecting URLs that look a certain way, it'd be nice to make it more robust.

Firstly, the URL can have a trailing slash which would cause your code to find an empty string.

Also, a URL can have a query string like ?foo=bar or a hash/fragment like #heading-2 appended. Your code would treat such things as part of the last "word" in the URL (or maybe the query string contains slashes too, which would split the URL in the wrong place).

Lastly, URLs can contain percent-encoded characters, which won't be decoded by your function.

Some test cases:

http://example.com/something           => "Something"
http://example.com/something/          => ""
http://example.com/something?q=foo     => "Something?q=foo"
http://example.com/something#id123     => "Something#id123"
http://example.com/something?q=foo#123 => "Something?q=foo#123"
http://example.com/some%20thing        => "Some%20thing"
http://example.com/something/#id123    => "#id123"
http://example.com/some%20thing?q=foo  => "Some%20thing?q=foo"

I trust you can see the problem.

Something like this is more robust, though I don't guarantee it's bullet-proof:

function lastWordCapitalized(url) {
  return url.replace(/^.*\/([^?#\/]+).*$/, function (_, word) {
    var word = decodeURI(word);
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
}

Which returns

http://example.com/something           => "Something"
http://example.com/something/          => "Something"
http://example.com/something?q=foo     => "Something"
http://example.com/something#id123     => "Something"
http://example.com/something?q=foo#123 => "Something"
http://example.com/some%20thing        => "Some thing"
http://example.com/something/#id123    => "Something"
http://example.com/some%20thing?q=foo  => "Some thing"

I should add, that all of this is assuming that

You're always dealing with absolute URLs. A link tag's href might just be "..", which is perfectly valid, but in which case there isn't much to display.
You always have some sort of path in the URL. If the URL just points to the domain's root (e.g. http://example.com/), you'll just end up upcasing the domain name.


@InheritConstructors is probably what you are looking for:

@InheritConstructors
class AnotherClass extends BaseClass {}

will create the constructors corresponding to the superclass constructors for you.


Your implementation can be greatly improved by using the System.Memory package. This will give you the new Memory<char> type (and if you're using .net-core it's already part of the SDK). With that you can create views of the string without creting any garbage.

At the same time you can make it more LINQ friendly. For this you can create the Slide extension that will return the slices of each part of the string and that accepts a Func for generating the offset for slicing. This one runs infinitely.

public static IEnumerable<(Memory<char> X, Memory<char> Y)> Slide(this string text, Func<int, int> calcOffset)
{
    var span = new Memory<char>(text.ToArray());
    while (true)
    {
        var offset = calcOffset(text.Length);
        var left = span.Slice(0, offset);
        var right = span.Slice(offset, text.Length - offset);
        yield return (right, left);
    }
}

You should also separate the logic for sliding and encapsulate each part in its own method. So you now have two of them.

public static Func<int, int> LeftToRight()
{
    var i = -1;
    return length =>
    {
        i++;
        if (i > length)
        {
            i = 0;
        }
        return i;
    };
}

public static Func<int, int> RightToLeft()
{
    var i = -1;
    return length =>
    {
        i--;
        if (i < 0)
        {
            i = length;
        }
        return i;
    };
}

To print it you can create another helper that encapsulates that part. Here you should replace the Thread.Sleep with Task.Delay which doesn't block/freeze the thread. With TimeSpan you can set the delay to whatever you want.

public static async Task PrintAsync(this IEnumerable<(Memory<char> X, Memory<char> Y)> source, TimeSpan delay)
{
    foreach (var element in source)
    {
        await Task.Delay(delay);
        Console.Clear();
        Console.Write(element.X);
        Console.WriteLine(element.Y);
    }
}

When you put everything together it'll look like that:

using  static Slider;

class Program
{
    static async Task Main(string[] args)
    {
        await
            "Hallo World"
                //.Slide(LeftToRight())
                .Slide(RightToLeft())
                .Take(20) // remove to run infinitely
                .PrintAsync(TimeSpan.FromMilliseconds(100));
    }
}

This is now garbage-free and does not create any additional sub-strings.


Python extended Euclidean algortihm + inverse modulo

Give your variables more meaningful names reflecting their role in the algorithm.


This unfortunately shows a rather erroneous understanding of the rule of three. Yes, all three methods are present, but they do not serve their expected purposes.

Your copy constructor doesn't free the old name before assigning the new one. That's a memory leak.
Your copy constructor dereferences an unitialized pointer. That's undefined behavior (almost certainly a segfault in this case).
Your assignment operator makes a shallow copy. Not only is it unintuitive to consumers since objects may affect each other, the destructors would attempt to double free the same object likely resulting in a segfault.

Provided the other two were fixed, your destructor is actually correct.

This code may technically compile, and it may even execute, but I would suggest that you run it through something like valgrind before continuing much farther. In addition, it might help to read more about the Rule of 3, learn about the copy and swap idiom, and learn about the Rule of 0, or more generally RAII and idiomatic resource management.

From a design/style perspective:

This isn't a Coordinate. It's a coordinate with a name, perhaps a NamedCoordinate. I would expect the x,y to be encapsulated in some kind of struct in real code and then a NamedCoordinate to contain an instance of that.
Arguments that are not modified should be taken by const reference rather than value. For example, void setName(string Name) makes an unnecessary copy of Name. This gets a bit more complicated in C++11, I'm afraid as your taking parameters by value would be correct, but you would missing std::move calls. Anyway, for C++ < 11, you just need to know that non-modified parameters should be taken by const reference.
using namespace std; is a bad habit
It's customary to leave off this unless it must be included in function calls or member accesses.
snake_case and camelCase are the standards for argument/parameter/member/etc names with either snake_case or PascalCase for classes. Your class name is good, but some of your uppercased parameter names are rather unusual.


Elegant way to replace substring in a regex with optional groups in Python?

import re

regex = re.compile(
    r'(The|A) '
    r'\w+'
    r'( is )'
    r'\w+'
    r'(?:'
        r'( and I )'
        r'\w+'
        r'( it)'
    r')?'
)

def repl(sentence, subject, colour, verb=None):
    m = regex.match(sentence)
    new = m.expand(rf'\1 {subject}\2{colour}')
    if m[3]:
        new += m.expand(rf'\3{verb}\4')
    return new

def test():
    assert repl('The sky is blue and I like it', 'bathroom', 'smelly', 'distrust') == \
        'The bathroom is smelly and I distrust it'
    assert repl('The tree is green and I love it', 'pinata', 'angry', 'fear') == \
        'The pinata is angry and I fear it'
    assert repl('A lemon is yellow', 'population', 'dumbfounded') == \
        'A population is dumbfounded'

Essentially, invert the sections of the regex around which you put groups; they're the things you want to save.


Continually refresh game data using AJAX

Reviewing your function

Looking at updateData() shows:

(reading signature only) there's no return value. So it does something inside, potentially modifying state (outside your function scope)
(reading body) it has two responsibilities: (1) retrieve data from server via http query; (2) actual update of variable data by assigning retrieved data to it.
it calls itself in two conditional branches. In fact it's a recursive function.

Improve:

(1) The function could return retrieved data. This would make it a pure function representing query part (of CQRS).

(2) This violates CQRS. You could improve by separating query (http data retrieval) from command (updating state: assigning a new value to a variable).

(3) recursive calls of same HTTP GET request in order to keep state up-to-date  are conceptually called long-polling. This polling is usually implemented as consecutive GET requests between intervals using a timer. To reduce unnecessary updates, the polling makes advantage of HEAD requests using modifiedSince header and E-tags (both telling if server has updated data or no change since last fetch).
A resource-friendly alternative to long-polling is the use of web-socket protocol.

Web-sockets

An event-based communication between server and client via a dedicated socket-connection. This connection is opened once allowing bi-directional asynchronous text-messages. Thus the server can send an update-notification (either including updated data or to allow the client to retrieve data in a separate GET request).

There are web-socket libraries for both JavaScipt (client) and PHP (server).


This is a decent way to implement Dependency Inversion, from the standpoint of your implementing classes. The only improvements I would recommend is to find a good class library that does the lookup of dependencies for you.

Really Inversion of Control/Dependency Inversion involves several parts:

Writing your classes so that they receive their dependencies via one of three methods:

Constructor injection (like you have) new Foo(x)
Property injection a.foo = b
Setter injection a.setFoo(b)

An object factory that can turn a class name in the form of a String into a new object
An dependency resolver that does the lookup of dependencies and injects them into a new object
A "container" object allowing you to configure your dependencies and wire your classes together

I've created Hypodermic for this purpose, though I think it should be refactored to separate the "container" from the "dependency resolver" functionality. I would be interested in finding out if there are other Dependency Injection libraries out there for JavaScript.


Scan array for 3 consecutive numbers that sum to 7

Your code, is way too imperative to be idiomatic Ruby.

The only reasonable improvement is re-writing it from scratch:

def lucky_sevens?(numbers)
  groups_of_three(numbers)
    .any? {|group| group.inject(:+) == 7}
end

Knowing that inject(:+) means sum, this reads like English. Implementing groups_of_three is left as an exercise for the reader.


SQL Injection defense, so i made some changes to my script and it looks like this, can anyone confirm if it is good

Yes, you are using prepared statements correctly. You didn't post all your updated code, so just remember to always use prepared statements and to never directly put any variables in the query.

Returning early

Your code is quite nested, which makes it difficult to read. If I want to know what happens in the else cases, I have to try to find the matching else, which can be difficult.

If you return early / introduce guard clauses, you can avoid this:

if (!isset($object['email']) || !isset($object['password'])) {
    session_destroy();
    http_response_code(400);
    return;
}
$email = $object['email'];
$password = $object['password'];

$stmt = $mysqli->prepare("select id, password from members where email = ?");
if(!$stmt) {
    session_destroy();
    http_response_code(400);
    return;
}

$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($id, $password);
$stmt->fetch();

if(!$id) {
    session_destroy();
    http_response_code(406);
}

if (password_verify($object['password'], $password)) {
    $message = array('message' => 'Authentication Successful!');
    $_SESSION["id"] = $id;
    echo json_encode($message);
} else {
    $message = array('message' => 'Wrong Credentials, Authentication failed!');
    session_destroy();
    http_response_code(400);
     echo json_encode($message);
}
$mysqli->close();

Structure

Now, you sill have some duplication (session destroy and response code setting) which you may want to remove, for example by returning error codes or success messages from the function and only setting it once from the calling code.

Your code also does a bit too much for my taste (db interaction, printing, retrieving user input, session management, etc). You could introduce functions such as getUserByEmail, etc to structure your code.

Misc

4xx are client side errors, but a non-working prepare is actually a server error; you should return a 500.
406 has to do with content encoding, so it is definitely the wrong code to send when a user is not found. It is also generally good practice to handle wrong username and wrong password the same way as to not leak information.
Upper-case all your SQL keywords to make queries easier to read.


Game object structure for Minecraft server

I would prefer your second plan, with inheritence and mixin modules.  I'll restate their different uses, which I am sure you know:

Use inheritance to model relationships between objects (B is a A).
Use mixins to model behavior (C logs, D remembers its position).

Unless you have a need to dynamically add mixins, apply YAGNI and don't do it yet.  Wait until you have a compelling need for dynamic mixins, and use them only where needed.  Metaprogramming is a power tool, but it does make the code harder to follow.  Use it judiciously.


So you want the index of the maximum value in your collection. That's a lot of code for such a simple task.
Let's start at the top.
q_table_test.txt - The sample data supplied is rather ridiculous. The elements that will become "attribute values" are all the same. How do you know the code is correct if there is no maximum? Does it matter which index is returned?
QTable.apply(filename) - The number_attributes_per_instance should be a configuration parameter, or derived directly from the input data. What if you needed to support more than one number_attributes_per_instance?
You don't appear to know what a lazy val is and what it's for. Its usage here makes no sense.
There are no safety checks. The file text is loaded as if formatting errors can't happen.
getQTableFromFile() - Why is getResourceAsStream() wrapped in an Option and then unwrapped with a .get? That's like loaning your brother a dollar so that he can repay the dollar he borrowed from you yesterday. A lot of busy work that accomplishes nothing.
cleanData() - Very inefficient.
getArgMaxValue() - If the state parameter is faulty you go through the trouble of building a bogus qValues list and then the elaborate and convoluted steps of finding the index of its max value, of which there is none. If you're going to lie to the user why not just return remainingPositions.head and be done with it?

As a demonstration, here's a smaller yet safer implementation of the same basic outline.
import scala.util.{Try, Using}  //Scala 2.13.x

class QTable(bindings: Map[String, Array[Double]]) {
  def getMaxValueIdx(state              : String
                    ,remainingPositions : List[Int]
                    ) :Option[Int] =
    bindings.get(state)
            .flatMap(arr => remainingPositions.maxByOption(arr.lift))
}

object QTable {
  private def loadFromFile(filename :String) :Try[String] =
    Using(scala.io.Source.fromFile(filename)) {
      _.getLines().map(_.takeWhile(_ != '#').trim).mkString
    }

  private val recFormat =
    """([^,"\[\]]+)\s*,((\s*('\d*\.?\d*')\s*,?)+)""".r.unanchored

  def apply(filename :String) :QTable =
    loadFromFile(filename).flatMap{ data => Try {
      recFormat.findAllMatchIn(data)
        .map(m => m.group(1) -> m.group(2)
                                 .split("[,\\s]+")
                                 .collect{case s"'$n'" => n.toDouble}
            ).toMap
    }}.fold(err => {println(err); new QTable(Map.empty)}
           ,new QTable(_))
}

My q_table_test.txt file:
[
"1st 9 Tbl,'0','1','2','3','4','5','6','7','8', #table of 9 elements
"Short Tbl,   '7' , '1.1','.22', '3'  ,'12.0' , #mixed spacing
"Split Tbl, '17', '1.25', '.127', '300.003'     #1st part
          , '12.0', '4321', '.1234'           , #2nd part
"2nd 9 Tbl,'0.','0.9','0.8','0.7','0.6','0.5','0.4','0.3','0.2'"
]

testing:
val qx = QTable("bogus.txt")    // (No such file or directory)
qx.getMaxValueIdx("1st 9 Tbl", List(7, 2, 3))  // None

val qt = QTable("./q_table_test.txt")
qt.getMaxValueIdx("1st 9 Tbl", List(7, 2, 3))  // Some(7)
qt.getMaxValueIdx("1st 9 Tbl", List())         // None
qt.getMaxValueIdx("Short Tbl", List(2,3,0))    // Some(0)
qt.getMaxValueIdx("Short Tbl", List(2,3,990))  // Some(3)
qt.getMaxValueIdx("NoSuchTbl", List(5,0,8))    // None
qt.getMaxValueIdx("Split Tbl", List(5,0,8))    // Some(5)
qt.getMaxValueIdx("2nd 9 Tbl", List(7, 2, 3))  // Some(2)


Getting better speed from adjusting rows in a DockableToolBar

I have one little suggestion with regard to style. It is much better to invert your conditions to have the simpler code run first when it involves yielding control. It also helps you avoid excessive indentation.

var child:DockableToolBar = DockableToolBar(row.getChildAt(k));

//Skip the rest of the row if we can't move the first child up.
if (prevRowW + child.measuredWidth >= toolbar.width) {
    break;
}

//Move child.
child.parent.removeChild(child);
prevRow.addChild(child);
prevRowW += child.measuredWidth;
--k;


Writing a for loop to build a String using Streams

One issue is that you cannot consume a stream with index. You can more or less have the same result with a IntStream bounded to your list's size.

Then you just have map each int to a code with the same logic. And, finally, collect them (This is the only part where the Stream will shine).

String string = IntStream.range(0, codes.size())
            .mapToObj(i -> {
                String code = codes.get(i);
                code = "example".equals(code) ? "EX":code.toUpperCase();
                return String.format("%1$d~%2$s", i, code);
            })
            .collect(Collectors.joining("|"));


I'm going to assume that you already know about HashSet and ISet in the following review and are just missing the reinventing-the-wheel tag.

ICollection

You've got Add, Remove, Clear, Count, and Contains. If you add a CopyTo(T[] array, int arrayIndex) and bool IsReadOnly { get { return false; } } to your implementation then you can implement ICollection.

Why Dictionary?

Perhaps you'd be better suited with a HashSet<T> implementation? Correct me if I'm wrong but it doesn't appear you're actually using the boolean value of the dictionary, so you'd be better suited with a Hashset<T>.

Generics

You could create a generic implementation Set<T> fairly easily. And if you wanted to still allow your existing functionality then you'd use Set<object>.

Set Operations

Perhaps consider having your operator functions return the new set from their actions?

For example,

public Set UnionWith(Set input)
{
    var unionedSet = new Set(_items); // See suggestion below.
    foreach (var item in input.Where(x => _items.ContainsKey(item)))
    {
        unionedSet.Add(item, true);
    }

    return unionedSet;
}

Constructor

Adding the ability to give IEnumerable or ICollection of items in a constructor could be really helpful, especially if you have your set operations return new sets as suggested above.


Google People PHP best practise to get OOP

If I had  to make this OOP, I'd begin by hedging concerns :

a class for user data handling (retrieving the POST and using it)
a service (that you'd dependency inject) to handle the configuration of the Google Service
a GoogleUser class for encapsulating the result of the service and abstracting all those foreach

Then, orchestrate those in some kind of controller (I guess you have already since you use a $this->sendJson method)
I like custom Exception cascade but that's just me :
try{
  //everything working well
}catch(GoogleLoginException $e){
}catch(RequiredEmailException $e){
}catch(RequiredNameException $e){
}

GoogleSDK is notoriously verbose and looks a lot like enterprise java and is always a pain to make elegant.
In the end you'd have something like :

class LoginController{
   private $google;

   public function __construct(GoogleService $google){
     $this->google = $google;
   }

   public function oauthCallbackAction($postRequest){
     $code = $postRequest->get("code");
     try{
         $authentifiedClient = $google->authentifiedClientWithCode($code);
         $googleUser = $authentifiedClient->getMe();
         return $this->json([
                              "user_name" => $googleUser->getUserName(),
                              "email" => $googleUser->getEmail(),
                            ], 200);
     }catch(GoogleAuthException $e){   //thrown by GoogleService
             return $this->json("blah", 500);
     }catch(RequiredEmailException $e){ //thrown by GoogleUser::getEmail
             return $this->json("gimme email !", 400);
     }catch(RequiredNameException $e){  //thrown by GoogleUser::getUserName
             return $this->json("gimme name !", 400);
     }

   }

}


I'm not entirely sure I understand what this does, but here goes.

Mojolicious doesn't use Moose. I would think long and hard whether I'd extend a Mojo::Base class with Moose. Does this work properly?
There are several instances of required together with default and lazy in your new attributes. Those do not make sense together. If it's required it needs to be passed in at construction. There is no need to make it lazy then as it will always be there from the start.
Your default for both reject_filter as well as resolve_filter are subs that return undef implicitly. That means if you don't pass those in, everything is discarded. Is that the intended behavior?
Your class is a subclass of Mojo::Promise, so there is no need to call Mojo::Promise->all. It's got an inherited ->all method that you can call on $self. (Mojo::Promise->all) returns a new object, so this breaks.