There's a lot that you can streamline here. For your Point record:

; A 2D point representing a coordinate, or any pair of numbers
(defrecord Point [x y])

If you were only going to use a Point to represent a 2D Cartesian coordinate pair, this record may have some value, but not very much. The problem is the "or any pair of numbers" part. If you want to represent a pair of numbers in Clojure, just use a vector:

[4 2]

Vectors are very easy to destructure:

(defn prettify [point]
  (let [[x y] point]
    (str "(" x ", " y ")")))

(prettify [4 2])
;=> "(4, 2)"

Or if you want to just get the first or second element in a pair, you can do that as well:

(first [4 2])
;=> 4

(second [4 2])
;=> 2

You're creating a fair bit of extra work (e.g. the index-of functions) for yourself by representing your 2D world as a 1D vector. Using a 2D vector instead would eliminate the need for all three of those functions, as well as the Enviro record itself:

(def enviro (vec (repeatedly 10 (fn [] (vec (repeatedly 10 (fn [] (rand-int 10))))))))

(pprint enviro)
;; [[3 7 6 2 9 8 5 7 0 2]
;;  [0 6 4 7 1 7 0 7 1 9]
;;  [1 8 0 5 6 9 7 7 8 3]
;;  [7 9 0 8 4 3 3 7 8 6]
;;  [8 9 3 5 1 4 6 5 0 2]
;;  [6 2 3 2 9 4 8 0 3 1]
;;  [0 5 7 7 7 9 0 0 9 5]
;;  [3 8 9 8 2 0 6 3 1 9]
;;  [9 7 4 1 5 8 0 5 1 2]
;;  [9 9 1 9 4 6 3 1 8 2]]
;=> nil

(get-in enviro [4 2])
;=> 3

Or, if your matrix is sparse, you could use a map from points to values instead:

(def enviro (into {} (repeatedly 10 (fn [] [[(rand-int 10) (rand-int 10)] (rand-int 10)]))))

(pprint enviro)
;; {[2 8] 7,
;;  [5 4] 2,
;;  [4 2] 6,
;;  [7 8] 1,
;;  [9 6] 5,
;;  [1 7] 2,
;;  [2 6] 3,
;;  [6 0] 5,
;;  [3 5] 4,
;;  [0 1] 5}
;=> nil

(get enviro [4 2])
;=> 6

If you just use a plain hash map for this, you'll lose some of the spatial query capabilities of a vector, but you could get some of those back by using a quadtree or some other spatially indexed data structure. I'll leave it up to you to decide how to go about doing that in Clojure if you want to take that route.

Your generate-neighbor-points function looks pretty good. Since range and for return lazy sequences, your implementation doesn't have any real performance issues. If I were to write it myself, though, I would probably be a bit more terse:

(defn neighbors [point radius]
  (let [[xs ys] (map #(range (- % radius) (+ % radius 1)) point)]
    (for [y ys x xs :when (not= point [x y])]
      [x y])))

There's nothing wrong with just returning the sequence of neighbor points and then leaving it up to the caller to decide what to do with them. I wouldn't recommend complecting the "find all the neighbor points" logic and the "do something with each of those neighbor points" logic into the same function, because I think it would make more sense to put that second bit in a separate function:

(defn update-all [enviro points f]
  (reduce #(update-in %1 %2 f) enviro points))

Example (using the 2D vector enviro example above):

(pprint (update-all enviro (neighbors [4 3] 2) #(mod % 2)))
;; [[3 7 6 2 9 8 5 7 0 2]
;;  [0 6 4 7 1 7 0 7 1 9]
;;  [1 0 0 1 0 1 7 7 8 3]
;;  [7 1 0 0 0 1 3 7 8 6]
;;  [8 1 1 5 1 0 6 5 0 2]
;;  [6 0 1 0 1 0 8 0 3 1]
;;  [0 1 1 1 1 1 0 0 9 5]
;;  [3 8 9 8 2 0 6 3 1 9]
;;  [9 7 4 1 5 8 0 5 1 2]
;;  [9 9 1 9 4 6 3 1 8 2]]
;=> nil


Dynamic List Application as first Vue.js App

At the moment all your current hobbies only consists of a name. I think you could use a simple string instead of wrapping it in an object (for point 8 this is not possible though, of course).
No need to check if (!this.deleted) before setting this.deleted = true;
setStyle should be a computed property
You can use @click instead of v-on:click, you can also use :style instead of v-bind:style (just syntactic sugar)
I would put the v-if="deleted" on the <div id="deleted-message"> instead of the inner <p> element.


Linear Equation in Two Variables Solver using Python

Some comments:

Rename functions to follow the PEP8 naming convention, here.
Do not use range to iterate over the a list of elements, iterate directly over it. If you need the index, as in your case, use enumerate.
No need to wrap the boolean clauses in parenthesis, moreover you can use the truth(y) values directly, see truth value testing.
Is possible add comments on what does the function does.

After a first rewrite the code of your function should look something like this:

def get_index(a, b):
    """Get the index of and element or else return 'not found' """
    status = 0
    index = 0
    for i, element in enumerate(b):
        if element == a:
            index = i
            status = 1
            break
    if status:
        return index
    else:
        return "not found"

def get_string(a, b, c):
    """Build a sub-string from c starting on a"""
    string = c[a]
    for i in range(a + 1, b, 1):
        element = c[i]
        string = string + element
    return string

def lcm(a, b):
    """Find the least common multiple"""
    if a > b:
        larger = a
    else:
        larger = b
    i = larger
    while True:
        if (i % a == 0) and (i % b == 0):
            break
        else:
            i += larger
    return i

if __name__ == "__main__":
    assert get_index(1, [1, 2, 3]) == 0
    assert get_index(1, [2, 3]) == "not found"
    assert get_string(0, 3, "hello world") == "hel"
    assert lcm(2, 5) == 10

I added some (basic) test, to validate any further change you could make in the future to this functions.

The above comments are superficial, if you want speed and reliability use the functions provided by the standard library, in the end your functions should look like something like this:

from math import gcd

def get_index(a, b):
    """Get the index of and element or else return 'not found' """
    try:
        return b.index(a)
    except ValueError:
        return "not found"

def get_string(a, b, c):
    """Build a sub-string from c starting on a"""
    return c[a:b]

def lcm(a, b):
    """Find the least common multiple"""
    return abs(a * b) // gcd(a, b)

The lcm implementation uses the gcd, see more in the wikipedia page.


Circumference and Area of a Circle in COBOL

Is Lynda that woman from LinkedIn, or just some mate of yours? I wonder how good a teacher she is, and what her intent is. Is it to learn COBOL, or GnuCOBOL.

The reason I say that is that COBOL has Standards. The latest is 2014, which supersedes 2002, then there's 1985 and 1974. There is a 1968 Standard, but it is extremely unlikely that any current compiler in use is to that Standard.

There are current compilers to the 1974 Standard. However, I'd not recommend that as a lowest common denominator, because the 1985 Standard introduced so much that eases coding and use of COBOL.

If learning COBOL (or being taught COBOL) with the intention of using it in a paid job, I'd recommend sticking to the 1985 Standard.

There are also Language Extensions. Everyone has them. Sometimes they coincided, sometimes they don't. GnuCOBOL supports many Extensions from other compilers. However, again, if the aim is to learn COBOL to get a job, beware of the casual use of Extensions.

An area where there are an absolute plethora of Extensions (to 1985) is in human interaction. DISPLAY and ACCEPT can be entirely different beasts from compiler to compiler. To use them in a portable way, use their very simplest forms.

This is sometimes not easy, because although your PROCEDURE DIVISION use is simple, you are, unknowingly, using a GnuCOBOL extension which provides conversion when the target of ACCEPT is a numeric value. If you were to work on an IBM COBOL, the same code would not be reliable.

I agree with Bruce and Edward in their answers. Do something about how your program looks. Exactly what you do in a personal sense depends. Be aware that if you get a COBOL job, you will likely be working in a team, and there will likely be local standards for how your program looks, and how things are done. This eases the ability to pick up someone else's program. You will be able to suggest changes for "bad" practices, but if you can't win the argument, do what the others do at your site.

Next, not so much a COBOL thing as a "programming" thing, I hope, although there are COBOL specifics affecting it. Your program doesn't work.

You can take from the user a maximum value of 999.99 for a radius. Your definitions, specifically for the area, do not allow for a radius of that size.

In COBOL you have to think longer about such things, because definitions, except when they are not, are fixed in size. The size you have for your fields containing "area" are orders of magnitude off. The maximum area is over three million for your maximum radius, but you only allow for five integer digits in your definitions.

Edward suggests using a more accurate value for PI. This is not something to be done blindly. The precision of PI to use should be defined in the specification for the program, as should any and all other limits and required precision. You can't write a COBOL program and then say to the Accountant "well, it works the way I've defined it".

Readability of output is also important. Use separators for large numbers, and zero-suppress down to the single digit before the decimal point. Unless your specification says otherwise. Line the numbers in the output on the decimal point. Much easier to consume as a human reader. Or switch the output to columnar with headings. Depends on the spec.

Be careful of using VALUE clauses unnecessarily. All of your VALUE ZEROES (which I'd code as "VALUE ZERO", but what the heck) are unnecessary. All of those fields are targets before they are sources, so the value of zero will never be relevant to anything. Having the VALUE implies that the value has a significance, which is misleading when it does not. Don't worry, very few programmers actually do that :-)

Indentation is for meaning. If the indentation makes the meaning clearer, do it. If not, don't. There is no point that I can discern in indenting 01-levels beyond what is necessary, or paragraph/SECTION-names.

No one mentioned the commas. Don't use commas (except in literals). They have no meaning. Don't use semi-colons. They have no meaning. To confirm this, add this line anywhere in the PROCEDURE DIVISION and recompile.

        ,,,,;;; , , , ; ; ;

Still compile as before? Still run as before? What is the point then. Ok, how do you make it easier for a human to read when there are multiple targets/sources:

        ADD A
            B
            C                    TO D
                                    E
                                    F

The names are just for examples, and you should always use meaningful names, for everything. It helps the source code tell the story of the program.

If you are going to use comments, make sure they are accurate. Comments are never compiled, so are only ever "checked" by the human reader. Your comments have significant errors and misinformation. Don't do that. If you then find there is little to say in a comment, because you have structured your program, and used good names, feel free not to use many comments (subject to local standards, of course, which can at times be thoroughly stupid in this particular area).

Here's your program applying most of the above. I've left the ACCEPT changes as an exercise for you.

   IDENTIFICATION DIVISION.
   PROGRAM-ID. CIRCUMF.
  *    Obtain the Radius of a circle and THEN
  *    print out the Circumference and the area of the circle.
   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01  WS-PI                               PIC 9V9999
                                            VALUE 3.1415.
   01  WS-CIRCLE.
       05  WS-RADIUS                       PIC 999V99.
       05  WS-CIRCUMFERENCE                PIC 9(4)V99.
       05  WS-AREA                         PIC 9(7)V99.
   01  WS-DISPLAY.
       05  WS-DISPLAY-CIRCUMFERECE         PIC Z,ZZZ,ZZ9.99.
       05  WS-DISPLAY-AREA                 PIC Z,ZZZ,ZZ9.99.
   PROCEDURE DIVISION.
       DISPLAY
               "Enter the Radius"
       ACCEPT
              WS-RADIUS
       COMPUTE WS-CIRCUMFERENCE     = 2 * WS-PI
                                      * WS-RADIUS
       MOVE WS-CIRCUMFERENCE        TO WS-DISPLAY-CIRCUMFERECE
       COMPUTE WS-AREA              = ( WS-PI
                                        * ( WS-RADIUS
                                          * WS-RADIUS ) )
       MOVE WS-AREA                 TO WS-DISPLAY-AREA
       DISPLAY
               "The Circumferece is "
               WS-DISPLAY-CIRCUMFERECE
       DISPLAY
               "The Area is         "
               WS-DISPLAY-AREA
       STOP RUN
       .

For the ACCEPT, you should first DISPLAY to tell the user what they are doing, and the limits to what they enter. The target of the ACCEPT should be an alpha-numeric (PIC X field of some size) and you should process, including validation, what is entered and only treat it as a number within the permissible range if that is confirmed. Try running your program with 999999999.999999 as input, and ponder.

In looking at this, I encountered something curious, and have posted as a possible issue on the GnuCOBOL site at SourceForge.Net. On the ACCEPT, for any input value above 99.99 I get a zero as the second decimal place, even if I have entered a non-zero digit there.

Confirmed as a bug. The fix is in shortly.

I you are building your compiler from a package, or installing a pre-built one, a work-around for the issue:

       05  WS-RADIUS-OVERSIZE              PIC 9(4)V99.
       05  FILLER
           REDEFINES WS-RADIUS-OVERSIZE.
           10  FILLER                      PIC X.
           10  WS-RADIUS                   PIC 999V99.

And

       ACCEPT WS-RADIUS-OVERSIZE

Instead of the existing ACCEPT, and then use WS-RADIUS as previously.

The code will then continue to work even with the new compiler when updated.

You should clearly comment any code like that, that is a work-around for some issue or other.


Checking if website exists and adding +1

Eliminate potential logic error in return value

I'm assuming the purpose of this code is to let you provide the name you want for your subsite, and the code will give you an available name based on whether the provided name already exists. It does this by appending/incrementing a suffix to the provided name whenever there is a naming collision. If this is the case, your FormatMyHomieURL() function should return temp sans the mainSite prefix, not subsiteName  + i.

To walk through an example briefly, let's say you want to name a subsite AwesomeWeb. The code checks and AwesomeWeb doesn't exist, so it returns subsiteName + i which resolves to AwesomeWeb0. You then go ahead and create a subsite named AwesomeWeb0 and everyone is happy. One month later, you come along and decide to make a subsite named AwesomeWeb. The code checks and sure enough, AwesomeWeb doesn't exist (since you created AwesomeWeb0 last time), so the code returns subsiteName + i which again resolves to AwesomeWeb0. Now you're going to run into a naming collision.

Reduce the number of instantiated SPSite objects

You are only ever dealing with a single SPSite object in this code (the parent site that you are checking for subsites). Therefore, you don't really need to create and dispose of a new SPSite object in every iteration of your loop just to grab a subsite from it.

I recommend refactoring your code to instantiate the SPSite object outside of SubwebExists() and pass it in to SubwebExists() as a parameter, along with the name of the target subweb temp.


Supervisors and employees query, with a subselect and inner join

Unless I'm missing something there doesn't seem to be a reason for the
subselect, just join all three tables directly.  Also, INNER is the
default, so you could drop that prefix as well.

The query would then become something like the following:

SELECT cp_supervisor_properties.supervisor_id,
       persons.last_name,
       persons.first_names,
       cp_supervisor_properties.employee_job_profile_id,
       org_employees.last_name,
       org_employees.first_name,
       org_employees.job_code
FROM cp_supervisor_properties
INNER JOIN persons
  ON persons.person_id = cp_supervisor_properties.supervisor_id
INNER JOIN org_employees
  ON org_employees.employee_number = cp_supervisor_properties.employee_job_profile_id
LIMIT 100;

Without more information (about how the data looks and so) I don't see possible performance improvements.  If you have problems with the query time you should probably check for missing indexes on the join columns and in general look into query optimisation.


Find indices of two numbers such that they add up to a target

Both your solutions work, however they are inefficient. A warning sign is when you need to iterate the array you are iterating. Even if the inner iteration can exit early, always consider the worst possible situation.

return lst.reduce((res, x, i) => {  // << first iteration
  const j = lst.findIndex(y => target - x === y); // << second iteration

The result is \$O(n^2)\$ time complexity

Improved search

When ever you repeat a search over the same data many times you should consider using a Map or a Set

In this case we can take advantage of the fact that the values we have already looked at provide information about the values we want.

If we have the arguments ([1,2,3,5], 7) as we step over each item we can build map of the items we want. For 1, we need a 6, 2 needs a 5, 3 needs a 4, and when you get to 5 you know you need that value and thus have a result.

Thus we get a solution that is \$O(n)\$  time, exchanging CPU cycles for memory (\$O(n)\$ storage)

Example 1

function find2SumTo(arr, k){
    const lookFor = new Map();
    var i = arr.length;
    while (i--) {
        if (lookFor.has(arr[i])) { return [i, lookFor.get(arr[i])]  }
        lookFor.set(k - arr[i], i);
    }
} // Note no final return as data is know to always have a result

The functional approach.

You don't have to use the built in array functions, you can add to the Array.prototype a more useful function.

// Finds information related to an item
Array.prototype.findInfo = function(cb) { // Must be function() to bind array to this
    var i = 0;
    while(i < this.length) {
        const result = cb(this[i], i++, this);
        if (result) { return result }
    }
}

With the new array function you can solve the problem with

const find2SumTo = (arr, k) => arr.findInfo((x, i) =>
      arr.findInfo((y, j) => {
           if (i !== j && k - y === x) { return [j, i] }
      });

However it is still an \$O(n^2)\$ time solution.

Imperative functional

The better functional approach is the first solution (Example 1). Functional does not mean you have to use lots of functions. It means that your solution must conform to the functional rules, no side effect, be pure. The function can be as complex as you need to avoid breaking the rules.


A few pointers:

First, variable length arrays are only allowed in C99:

char buffer1[width + 1];

If the code is to be strictly ANSI C, one would make an pointer to an array and use a function like malloc or calloc to allocate some memory for the array:

char* buffer = malloc(sizeof(char) * (width + 1));

(Then, if necessary, the buffer would be initialized, or calloc used instead to initialize and allocate at once.)

Second, code readability:

if(second % 2 == 0){
    second = second - 2;
}else{
    second = second - 3;
}

Could be better written as:

if (second % 2 == 0) {
    second = second - 2;
} else {
    second = second - 3;
}

It may seem like nitpicking, but it does make it easier for people to read your code and understand what is going on. Coding is a form of communication as well -- make it easier for others to read, and it others will be able to better understand what you're trying to achieve.

The switch statement could be similarly improved:

switch(*argv[1]){
    case '1': lattice();break;
    case '2': normal();break;
    default: printf("1 = lattice effect | 2 = static effect\n");break;
}

To:

switch(*argv[1]) {
    case '1':
        lattice();
        break;
    case '2':
        normal();
        break;
    default:
        printf("1 = lattice effect | 2 = static effect\n");
}

Also, adding line breaks between certain blocks of statement which perform one task may improve readability.

There seems to be copious use of while loops, but I don't see a single for loop -- for loops are probably more useful for performing "counter"-type activities, such as performing repetitions for a certain number of iterations:

int i;
for (i = 0; i < 100; i++) {
    /* Action to perform 100 times */
}

The basic structure of a for loop is as follows:

for (initial-condition; loop-condition; expression-on-each-iteration) {
    /* Action to perform on each iteration. */
}

(Note: The name for the conditions are not official names, I just made them up to describe what they're for.)

The initial-condition is what to do when the for loop first begins. Many times, this is used to initialize a counter variable to some value. For example, i is set to 0.

The loop-condition is an expression that is evaluated at the beginning of each iteration which determines whether the loop should continue. If the expression is true, then the loop is performed, but if false, then the loop terminates.

The expression-on-each-iteration is something that is performed at the beginning of each iteration of the loop, if that iteration is to take place. Commonly, this is part is used to increment the counter used to control the loop.


Update:
Well, if someone wants to know, I've done some changes for good,
one of the main problems I had was that I couldn't really "connect" the GameStates to the main Engine itself without passing a pointer to the engine (wich is messy) or individual pointers to the InputHandler, Display, etc.
The thing was that for example the InputHandler handled the Window events and the keyboard input, so for a GameState to have access to it, I would have to create a pointer to Game::InputHandler, so I did a few things:
First I created a KeyboardHandle class wich is totally independent from the Engine itself and its only function its to get keyboard input, that way I can make every game state to have an independent KeyboardHandle, also every game state has a pointer to the engine Display class, that means that from the game state you can get access to information like windows size or the SDL_Renderer without having much trouble, you add states from the Engine so the Display pointer is set at that moment.
The GameState class is the base for all games, now it looks like this:
#pragma once
#include "KeyboardHandle.h"
#include "TextureManager.h"
#include "Display.h"

class GameState{
protected:
      KeyboardHandle keyboard;
      TextureManager texture_manager;
      Display * screen_display;
public:
      GameState(Display * display){ this->screen_display = display; }
      virtual void onStart() = 0;
      virtual void handleInput() = 0;
      virtual void onUpdate(float) = 0;
      virtual void onRender() = 0;
};

As you can see is almost all independent from the Engine, it just shares the display so we can render the graphics.
Here is an example state (drawing an image on the center of the screen):
#include "GameState.h"
#include "Entity.h"

class DefaultState : public GameState{
      Entity splash_logo;
public:
      DefaultState(Display * display) : GameState(display){ }

      void onStart(){
            texture_manager.Load("textures/splash_logo.png", "splash_logo", screen_display->GetRenderer());
            splash_logo = Entity("splash_logo", Vector2i(0, 0), Vector2i(336, 336), 1.0f);

            float center_x = (screen_display->GetWindowWidth() / 2) - splash_logo.GetCollisionBox().w / 2;
            float center_y = (screen_display->GetWindowHeight() / 2) - splash_logo.GetCollisionBox().h / 2;
            splash_logo.SetPosition({center_x, center_y});
      }

      void handleInput(){

      }

      void onUpdate(float delta_time){

      }

      void onRender(){
            texture_manager.Draw(splash_logo.GetSprite(), splash_logo.GetPosition(), screen_display->GetRenderer());
      }
};

And just for fun here is the dependency diagram:


I think the code is a little dodgy, and the design is dodgy. I'd store the translation in a dictionary of some sort.

But addressing your immediate question, to simplify the code you have, you could do....

public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture)
        {
            var product = DoSomeMagicToGetAProduct();

            var arText = culture == "ar" ? text1 : text2;
            var enText = culture == "en" ? text1 : text2;
            var updateEn = culture == "en" ? edit1 : edit2;
            var updateAr = culture == "ar" ? edit1 : edit2;

            if (element == "title")
            {
                if (updateEn) product.Title = enText;
                if (updateAr) product.TitleAr = arText;
            }

            if (element == "description")
            {
                if (updateEn) product.Description = enText;
                if (updateAr) product.DescriptionAr = arText;
            }

            if (element == "excerpt")
            {
                if (updateEn) product.Excerpt = enText;
                if (updateAr) product.ExcerptAr = arText;
            }

            product.Save();

        }


Your code looks good. It's always nice to see people following PEP 8. There is a small issue though with how you check if a list is empty or not. Currently you write
elif not len(exclude_stack): or elif num == 9 and len(exclude_stack): but PEP 8 actually has the following recommendation for this kind of tests:

  For sequences, (strings, lists, tuples), use the fact that empty
  sequences are false.

Yes: if not seq:
     if seq:

No:  if len(seq):
     if not len(seq):

So, in your case, it should be elif not exclude_stack: and elif num == 9 and exclude_stack:.

Additionally, the details on implementation in the docstring look redundant, I would remove them and leave only the task description.

The main question I have regarding your implementation is: Do you really need to have the stack to keep track if you are inside the 6-9 section? If I print exclude_stack for this input summer_sum([6] * 10 + [9] * 10), it will look like this:

[0]
[0, 0]
[0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0]
[0, 0]
[0]
[]

This doesn't really look like the most optimal solution memory-wise. How about keeping a track of the 6-9 sections by simply incrementing/decrementing some integer variable instead? Something like this:

def summer_sum(a_list):
    """Solution for Summer 69 challenge"""
    section_depth = 0
    total = 0
    for num in a_list:
        if num == 6:
            section_depth += 1
        elif section_depth == 0:
            total += num
        elif num == 9 and section_depth > 0:
            section_depth -= 1
    return total

I assume this will be also a bit faster as you won't have to pop or append to a list.

My hands are also itching to remove the total variable and make a generator function, but this may be a bit overboard:

def summer_sum(a_list):
    """Solution for Summer 69 challenge"""

    def free_numbers(numbers):
        section_depth = 0
        for num in numbers:
            if num == 6:
                section_depth += 1
            elif section_depth == 0:
                yield num
            elif num == 9 and section_depth > 0:
                section_depth -= 1

    return sum(free_numbers(a_list))


Efficient way of flat mapping a range of a multidimensional random access collection

I gather that your intent was to write a method that iterates through an array of arrays (but avoiding functional patterns), flattening the results in the process such that given...

let a = [["0", "1", "2", "3", "4", "5"], ["6", "7"], [], ["8","9","10","11", "12"], ["13","14", "15"]]

... that result for 5..<10 would be ["5", "6", "7", "8", "9"]

Assuming that’s what you were trying to do, I think you can simplify it:

extension Array {
    func flattened<T>(range: Range<Int>) -> [T]? where Element == Array<T> {
        var result: [T] = []

        var offset = range.startIndex
        var length = range.upperBound - range.lowerBound

        result.reserveCapacity(length)

        for subarray in self {
            let subarrayCount = subarray.count
            if offset < subarrayCount {
                if length > subarrayCount - offset {
                    result += subarray[offset...]
                    length -= subarrayCount - offset
                } else {
                    return result + subarray[offset..<offset + length]
                }
            }
            offset = Swift.max(0, offset - subarrayCount)
        }

        return nil
    }
}

In terms of observations on your code:

I wouldn’t advise get method name. It’s not very meaningful name and only conjures up confusion with getters. I’d go with something that captured the “flattening” nature of the routine.
As a general rule, we should avoid closures with side-effects in functional programming patterns. Even though you’ve written an “iterative” rendition of the OP’s code, you’re using a functional method, firstIndex, and you are updating variables outside the closure. It’s technically allowed but is contrary to the spirit of functional programming patterns and is dependent upon the implementation details of firstIndex.


Generate String with Random Consonants and Vowels in C

This is generally quite pleasant. Only a few observations:

Character input loop

The construct

for (int c; (c = getchar()) != EOF;)

is a little easy to misread.

I'm always very tempted to use a for loop for this kind of thing (also various kinds of pointer manipulation of a similar form) but it tends to end up being rather awkward.

while ((c = getchar()) != EOF)

Is an overwhelmingly common C idiom, and I'd be inclined to use that form instead (even if you do end up with a slightly lonely-looking variable declaration at the top).

Redundant reference data

As another answer pointed out, it seems a bit superfluous to maintain completely separate sets of reference data for upper- and lower- case letters. Using toupper in to_char would be one approach; personally, I would be tempted to wrap to_char in another function which checked the case of its argument and called toupper as appropriate---but that might feel like overkill for only a couple of character classes.

The explicit list of consonants also feels a little funny to me. I think of consonants as "those letters which are not vowels", and there enough of them that I'd have to think far too hard if I were to type them all out. I'd be certainly tempted to generate the consonant set at runtime, iterating over the range 'a' to 'z' and excluding the vowels (which I would explicitly enumerate).

Naming: to_char

The signature char to_char(char c) looks a little odd to me. Converting characters to characters? I'd probably instinctively reach for something like

char gen_char(char kind)

(for generate character), but that's open to debate.

Redundant breaks

The break statements in to_char don't hurt, but they are dead code, so they take up mental space. I would be inclined to drop them---and to align the return from the default case with the others, to emphasise that all of the cases return directly.

No return from main

I know that the C standard allows it, but it will still always look wrong to me. Depending on the context for this program, other people might look at the source and have mental space occupied by the sense that the lack of a return from main looks wrong. But that is essentially entirely a matter of opinion, and arguably I'm the one that's wrong there.

As I said though, overall it's really rather pleasant.


Comments on SASS from CSS for a SASS beginner

Some comments on your style of selecting:

div.pagination is overqualified. A container is almost always going to be a div, so you just can write .pagination
In many cases, there is no use for an extra container. You might as well apply the pagination class to the list itself: <ul class="pagination">
You also have a lot of redundancy in your selectors because you always use ul and li in the chains. This is not necessary and could be made easier:

.pagination ul {}

/* li's can only appear in lists, no need to add it to the selector */
.pagination li {}

/* The only links inside your pagination are usually in relation to the pagination */
.pagination a {}

If you have lists inside your pagination that need separate styling, use separate classes or place them outside of the actual pagination
Don't overqualify the .active and .disabled classes as well. They will end up being on the list items anyway

Conclusion:

You nest far too deep. Avoid nesting selectors deeper than 2–3 levels. Otherwise you get bloated CSS like this.

Compare my SCSS to yours:

.pagination {
    display: block;
    height: 24px;
    margin-left: -5px;

    li {
        float: left;
        display: block;
        height: 24px;
        color: #999;
        font-size: 14px;
        margin-left: 5px;

        &:hover a {
            background: $bgltblue;
        }

        &.disabled {
            a {
                cursor: default;
                color: #999;

                &:hover,
                &:focus {
                    background: transparent;
                }
            }
        }

        &.active {
            a {
                background: $headblue;
                color: white;
                font-weight: normal;
                cursor: default;

                &:hover,
                &:focus {
                    background: $headblue;
                }
            }
        }
    }

    a {
        display: block;
        padding: 1px 7px 1px;
        color: #555;
        font-weight: normal;

        &:focus {
            background: $bgltblue;
        }
    }
}


Insertion of a node in M-way search tree

This looks more like C than C++.
The only features of C++ I see used are #include <iostream>, using namespace std; and new.
Since this is flagged c++, I will review it as such, but if it is intended to use with C, a review for that language might give better insights.

Don't reinvent the wheel
The C++ standard library provides many features that would help. Need a sorting algorithm? Use std::sort. Need to find something in a container? Use std::find, std::lower_bound, std::upper_bound or some other algorithm that suits your needs!
Naming
Many variables have very short and cryptic names. This makes the code hard to read.
Example: What does mWay::k stand for?
Issues

Elements of <iostream> aren't used anywhere.

using namespace std; is discouraged, especially in headers. If someone else includes that header, it might cause ambiguities in their code!

Design
C++ has classes. Why not use them to define the tree, instead of a loose set of free standing functions?
For example, a rough outline could look like this:
#include <array>
#include <memory>
#include <algorithm>

template<typename ValueType, size_t Arity>
class nary_search_tree {
    static_assert(Arity >= 2u, "Tree needs an arity greater than or equal to 2!");

    class node {
        size_t size = 0;
        std::array<ValueType, Arity-1> values;
        std::array<std::unique_ptr<node>, Arity> children;

        void insert_in_order(ValueType value) {
            auto insert_index = find_child_index(value);

            if(insert_index == size) {
                values[insert_index] = value;
                ++size;
                return;
            }

            std::copy_backwards(&values[insert_index], &values[size-1], &values[size]);
            values[insert_index] = value;
            ++size;
        }

        void find_child_index(ValueType value) const {
            for(auto i = 0u; i < size; ++i) {
                if(values[i] > value) return i;
            }

            return size;
        }

    public:
        void insert(ValueType value) {
            if(index < values.size()) {
                insert_in_order(value);
                return;
            }

            auto index = find_child_index(value);
            if(!children[index]) {
                children[index] = std::make_unique<node>();
            }

            children[index]->insert(value);
        }
    };

    std::unique_ptr<node> root = nullptr;

public:
    void insert(ValueType value) {
        if(!root) root = std::make_unique<node>();

        root->insert(value);
    }
};

Makes reasoning much easier, doesn't it? And as a bonus, it's much more generic, too!
Note: This code requires C++11 or later to work.

Of course, this is just the beginning... This code could be improved, e.g. by using const ValueType& to prevent copies and by using overloads for ValueType&& to support movable types. Also, other search tree functionality is missing, like looking up an element


It looks mostly fine. I only have three comments:

The definitions of zero_to_nineteen and tens  is too long for my taste. It will look more readable like this::

tens = ("zero", "ten", "twenty", "thirty", "forty",
        "fifty", "sixty", "seventy", "eighty", "ninety")

Reject floats straight away is too much. One cannot then ask for the spelling of 1e6. I would do:

if isinstance(number, float):
     if number % 1 == 0:
         number = int(number)
     else:
         raise ValueError("number must be an integer")

elif not isinstance(number, int):
     raise ValueError("number must be a number")

Note that your function would happily accept things like 1j, "abc", None...
For Guido's beard, don't roll your own log function! use int(math.log10)


We wouldn't normally put the function definitions in the header like that.  Just write the declarations that are needed by the calling code, and put the definitions into their own source file.
It seems odd to have these function pointers:

bool (*push)(struct int_stack *, int);
bool (*pop)(struct int_stack *, int *);
int (*size)(struct int_stack *);
void (*print_stack)(struct int_stack *);

Nothing needs them, so just omit them.
pop() uses size() before the latter is defined.  We could solve this by re-ordering, but separating declarations from definitions will naturally fix this.
size() and print() don't need to modify the stack, so they should accept pointer to const object.
The function names are all vulnerable to collisions.  I'd suggest adding a common prefix to distinguish and group them.
Writing zeros to the unused elements is a bit pointless, as those elements are not reachable through the public interface.
Here's my re-write:
Header:
#ifndef INT_STACK_H
#define INT_STACK_H

#include <stdbool.h>

typedef struct int_stack int_stack;

int_stack *stack_create(void);
void stack_free(int_stack *self);

bool stack_push(int_stack *self, int item);
bool stack_pop(int_stack *self, int *out);
int stack_size(const int_stack *self);
void stack_print(const int_stack *self);

#endif // !INT_STACK_H

Implementation
#include <stdio.h>
#include <stdlib.h>
#define STACK_MAX 1000

struct int_stack {
    int top;
    int data[STACK_MAX];
};

int_stack *stack_create(void) {
    int_stack *stack = malloc(sizeof *stack);
    if (stack) {
        stack->top = 0;
    }
    return stack;
}

void stack_free(int_stack *self) {
    free(self);
}

bool stack_push(int_stack *self, int item) {
    if (self->top == STACK_MAX) {
        return false;
    }
    self->data[self->top++] = item;
    return true;
}

bool stack_pop(int_stack *self, int *out) {
    if (stack_size(self) == 0) {
        return false;
    }
    *out = self->data[--self->top];
    return true;
}

int stack_size(const int_stack *self) {
    return self->top;
}

void stack_print(const int_stack *self) {
    printf("| top |\n");
    for (int i = self->top-1; i >= 0; i--) {
        printf("| %3d |\n", self->data[i]);
    }
}


Test a number for primality and return smallest divisor different from 1 if it’s is composite

Single responsibility principle

You method smallestDivisor() violates the SRP because it does too many things.

It is

calculating the smallest divisor
calculating primes
checking if the number is neither composite nor prime

You should consider to just calculate what the name of the method tells you.

Method names should be made out of a verb or a verb phrase, so getSmallestDivisor() would be better.

So how to handle the edge cases ? That is easy, add methods to evaluate them.

private static boolean isPrime(int number, int smallestDivisor){
    return number == smallestDivisor;
}

private static boolean isComposite(int number, int smallestDivisor){
   return number != smallestDivisor && smallestDivisor > 1;
}

The getSmallestDivisor() method should then return as shown below

public static int smallestDivisor(int primeCandidate) {

    if (primeCandidate =< 1) {
        return primeCandidate;
    }
    if (primeCandidate % 2 == 0) {
        return 2;
    }
    if (primeCandidate % 3 == 0) {
        return 3;
    }

    // Checks divisability of numbers in the form of 6k+1 and 6k-1.
    // It starts with: 5 and 7, 11 and 13, 17 and 19, 23 and 25, ...
    for (int i = 5; i <= sqrt(primeCandidate); i += 6) {
        if (primeCandidate % i == 0) {
            return i;
        } else if (primeCandidate % (i + 2) == 0) {
            return i + 2;
        }
    }

    return primeCandidate;
}

to be tested like:

    int smallestDivisor = getSmallestDivisor(primeCandidate);
    if (isPrime(primeCandidate, smallestDivisor)) {
        System.out.println(primeCandidate + " is prime.");
    } else if (isComposite(primeCandidate, smallestDivisor)) {
        System.out.println(primeCandidate + " is composite and has the smallest divisor " + smallestDivisor + ".");
    } else {
        System.out.println(primeCandidate + " is neither prime nor composite.");
    }

Input

you haven't checked an edge case: that a user might not pass any argument into the application.
you should extract the reading of the argument to a separate method and maybe add a possibility, if the given input doesn't match the requirements, to enter the value again. So e.g no arguments provided, value < 0 or not an integer.


PHP Shopping Website with Cart - Returning a HTML String

You might want to decompose it into smaller pieces that will be easier to follow and eventually modify.

You could also learn a bit about dependency injection. Creating new instances all around anytime you need them is not very good.

Here is a very simple rewrite of your code and a lot of pieces are missing but I hope it gives some general guideline.

It uses PHP 7.4 features, if you can't use those, of course ignore all the typehints, etc..

Also it might make sense to depend on interfaces instead of classes directly, but didn't want to go this far as I think it could be too much for you at one go.

Dont be shy to define structures.

class Product
{
  public int $id;
  public string $name;
  public float $price;

  public function __construct(int $id, string $name, float $price)
  {
    $this->id =  $id;
    $this->name = $name;
    $this->price = $price;
  }
}

Create product repository

class ProductsRepository
{
    /**
     * @param array<int> $ids
     * @return array<int, Product>
     */
    function getProducts(array $ids): array
    {
        // get it from somewhere
    }
}

Structure for item in cart holds a bit more.

class CartItem
{
  public int $productId;
  public string $name;
  public float $unitPrice;
  public int $quantity;
  public function __construct(int $productId, string $name, float $unitPrice, int $quantity = 1)
  {
    $this->productId = $productId;
    $this->name = $name;
    $this->unitPrice = $unitPrice;
    $this->quantity = $quantity;
  }
  public function getTotalPrice(): float
  {
    return $this->unitPrice * $this->quantity;
  }
}

Cart holds many items, allows to iterate them, and add them and it knows the product repository to allow it doing so.

class Cart
{
  private ProductsRepository $products;
  /** @var array<CartItem> */
  private array $items;
  public function __construct(ProductsRepository $products, array $items = [])
  {
    $this->products = $products;
    $this->items = $items;
  }
  public function getItems(): array
  {
    return $this->items;
  }

  public function getTotalPrice(): int
  {
    // count it here, or have it in property and make sure it is updated while adding items.
  }

  public function add(int $productId, int $quantity = 1)
  {
    if (isset($this->items[$productId])) {
      // already in cart => increase quatity
    } else {
      $product = $this->products->getProduct($productId);
      //handle product not exists, not on stock, etc.
      $this->items[$productId] = new CartItem($product->id, $product->name, $product->price, $quantity);
    }
  }
}

We will store cart in session, this will take care of it.

class CartSessionStorage
{
  // we need it for the Cart instances
  // and maybe we wont store product names in session but load them from products repo?
  private ProductsRepository $products;

  public function loadCart(): Cart
  {
    // load from session
  }
  public function saveCart(Cart $cart): void
  {
    // save to session
  }
}

Renderer knows the html structure and some localization/formatting rules.

class CartRenderer
{
  private Formatter $formatter;
  public function __construct(Formatter $formatter)
  {
    $this->formatter = $formatter;
  }
  public function renderCart(Cart $cart): string
  {
    $html = '';
    // your rendering here;
    foreach ($cart->getItems() as $item) {
    //you can use heredoc, but add some html escaping, nor heredoc nor your code handle it
    $html .=
      <<<HTML

write html here
and dont mind if u use {$item->getTotalPrice()}
      HTML;
    }
    return $html;
  }
}

Put it all together.

$products = new ProductsRepository();
$storage = new SessionCartStorage(products);
$formatter = new Formatter();
$renderer = new CartRenderer($formatter);

And there you go.

$cart = $storage->loadCart();

// form submission?
$cart->add($productId, $quantity);
$storage->saveCart($cart);

// render it
echo $renderer->renderCart($cart);


Welcome to the world of beginner Python programming, and programming in general!  Python is a nice language to learn and start out with!

Allow me to give you some tips and pointers, with the hope that you will be able to learn a little from them.

Also, allow me to apologize in advance for this massive wall of text.  I may have gone a little bit overboard in my review and analysis, but I wanted to make sure you would understand my revisions and some of the code I've added, in the event you are unfamiliar with the functionality I implement and use in the reviewed and revised code.

Add white space for readability, and obey PEP8 rules for whitespace around assignment and equality operators

Python is extremely indentation-based.  This means an indent usually indicates a code block that needs executed underneath of another one (such as your if statements have, etc).

However, Python also benefits from having white space added at logical locations for readability.  I usually define these locations as between loops and other sections of code, between functional statements (addition, subtraction, etc.) and output, between the end of an if statement and the beginning of its elif or else blocks, after the end of an entire if block, etc.

There is also a rule for Python code style, called the PEP8 which dictates whitespace around assignment statements, equality operators (such as ==), and also arithmetic operators (+, -, *, /, and others), stating that a space is necessary around them.

This is your code with the whitespace per my guidelines and the PEP8 guidelines.  My further reviews from here will be using this as a base.

while True:
    print('Options:')
    print('Enter \'a\' to add two numbers')
    print('Enter \'s\' to subtract two numbers')
    print('Enter \'m\' to multiply two numbers')
    print('Enter \'d\' to divide two numbers')
    print('Enter \'q\' to quit the program')

    response = str(input(':')).lower()

    if response == 'q':
        break

    elif response == 'a':
        while True:
            try:
                num1 = float(input('Enter a number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        while True:
            try:
                num2 = float(input('Enter another number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        result = num1 + num2

        print('The answer is ' + str(result))
        print()

    elif response == 's':
        while True:
            try:
                num1 = float(input('Enter a number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        while True:
            try:
                num2 = float(input('Enter another number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        result = num1 - num2

        print('The answer is ' + str(result))
        print()

    elif response == 'm':
        while True:
            try:
                num1 = float(input('Enter a number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        while True:
            try:
                num2 = float(input('Enter another number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        result = num1 * num2

        print('The answer is ' + str(result))
        print()

    elif response == 'd':
        while True:
            try:
                num1 = float(input('Enter a number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        while True:
            try:
                num2 = float(input('Enter another number:'))
                break
            except(TypeError, ValueError):
                print('*(Input Error) Enter valid number*')
                continue

        result = num1 / num2

        print('The answer is ' + str(result))
        print()

    else:
        print('*Unknown input*')

    continue

Move non-quit responses to separate "if" block, so we can do some tasks without repeating code.

One of the major guidelines of programming is that if you are doing something that requires you to copy and paste code in all the time to do the same thing, chances are there's a better implementation.

You currently do this in every single block of code under each conditional check for the response entered, except for quitting and invalid responses:

while True:
    try:
        num1 = float(input('Enter a number:'))
        break
    except(TypeError, ValueError):
        print('*(Input Error) Enter valid number*')
        continue

while True:
    try:
        num2 = float(input('Enter another number:'))
        break
    except(TypeError, ValueError):
        print('*(Input Error) Enter valid number*')
        continue

We can easily move this to outside the if block, if we separate the a, s, m, and d response checks to somewhere else, so we don't have to repeat all the code, which actually will save you a lot of lines of code.  This is the new set of if/elif statements, with the 'quit' response checked before we even begin to look at other responses, and the deletion of the "else" clause that you had in there:

if response == 'q':
    break

while True:
    try:
        num1 = float(input('Enter a number:'))
        break
    except(TypeError, ValueError):
        print('*(Input Error) Enter valid number*')
        continue

while True:
    try:
        num2 = float(input('Enter another number:'))
        break
    except(TypeError, ValueError):
        print('*(Input Error) Enter valid number*')
        continue

if response == 'a':
    result = num1 + num2

elif response == 's':
    result = num1 - num2

elif response == 'm':
    result = num1 * num2

elif response == 'd':
    result = num1 / num2

Note that while I drop the "Unknown Input" check (that else statement at the end), we're going to add it back in elsewhere in the code in my next recommendation.

Move "Invalid Input" check to second thing checked in the if/elif block for "Quit" checking

This recommendation builds from the previous recommendation above this one; it should not be implemented without the previous recommendation, as it builds off of the previous recommendation

You'll note that I removed the else block that handled "Unknown Input" captures in my earlier recommendation.  That's because we can implement it in a better place, and earlier on in the code, and handle things as a "Check if input is valid before anything else" approach, which is what we'll cover in this section.

Basically, we don't need to put the "Invalid Input" check at the bottom.  Instead, we can check it at the beginning!

This is the code that will do that:

if response == 'q':
    break
elif response not in 'asmd':
    print('*Unknown input*')
    continue

Because you're a beginner, let me break down the elif here.  Basically this says "Is the value of response contained within this string of valid response characters?", and if it is not, then it will print the "Unknown Input" error, and continue on to the next iteration of the loop - skipping all other code below it.

Unnecessary continue statement at end of loop

In your original code, you have the continue statement at the end of the code underneath the while loop.  This is unnecessary - when the end of the code under the loop is reached, it will automatically continue on to the next iteration, and you don't need the continue statement here.

You can just remove that continue statement.

Improper checking of 'length' of response

This builds off my two earlier recommendations for changing your if and elif blocks for "Quit" and "Invalid Response" to their own block at the beginning, and then have a separate if/elif block for response checking only.

So, in my recommendations, I don't properly check the length of the response provided.  That means I potentially introduce breakage where it's listed as "unknown input"  So, let's do that as part of "Invalid Input" checks, by checking if the length of the response is greater than one, or if it's not in the 'valid responses' we defined.  The code below does that.

if response == 'q':
    break
elif len(response) > 1 or response not in 'asmd':
    print('*Unknown input*')
    continue

Make Output and Options Prompt a little cleaner

This is more or less up to each programmer, but I believe that the output and prompts you use are a little... cluttered, and harder to read.  I also believe input could be better handled in terms of providing users with the prompt.

Let's start with the options prompt first.  We can reorganize and revise these to make output a little nicer, and grab the option in a nicer way than just a colon and a prompt line:

print('Enter \'a\' to add two numbers')
print('Enter \'s\' to subtract two numbers')
print('Enter \'m\' to multiply two numbers')
print('Enter \'d\' to divide two numbers')
print('Enter \'q\' to quit the program')

response = str(input('Select an option: ')).lower()

Note that we got rid of that first print("Options:") item.  You can add it back in if you want.

Next, let's work on the prompts for the two numbers being worked with, and the output.  I think it would benefit from some line breaks to sort of 'separate up' the content to make it a little more readable.

I'd like to introduce you to an escaped character sequence: \n.  In a string, \n is interpreted as a line break, which generates a blank line in the usages I'm putting in place here when actually displayed to the user.

The following lines should be changed accordingly, to make your output a little nicer:

num1 = float(input('Enter a number:')) should become num1 = float(input('\nEnter a number: '))
num2 = float(input('Enter another number:')) should become num2 = float(input('\nEnter another number: '))
print('The answer is ' + str(result)) should become print('\nThe answer is ' + str(result) + '\n')
print() should become print('------------------\n').

This results in program output a little like this, then (using a, 1, and 1):

Enter 'a' to add two numbers
Enter 's' to subtract two numbers
Enter 'm' to multiply two numbers
Enter 'd' to divide two numbers
Enter 'q' to quit the program
Select an option: a

Enter a number: 1

Enter another number: 1

The answer is 2.0

------------------

Enter 'a' to add two numbers
Enter 's' to subtract two numbers
Enter 'm' to multiply two numbers
Enter 'd' to divide two numbers
Enter 'q' to quit the program
Select an option: q

Avoid escaping ' characters, by using " around the strings containing them

This was originally pointed out in comments by Dex'ter.

In your print statements where you print out the list of available options for the user, you can avoid having to use \' to escape the 's by using the quotation marks around the entire string instead of apostrophes., like so:

print("Enter 'a' to add two numbers")
print("Enter 's' to subtract two numbers")
print("Enter 'm' to multiply two numbers")
print("Enter 'd' to divide two numbers")
print("Enter 'q' to quit the program")

Complete Code, After Recommendations

This is the code, after all my recommendations from above implemented, in its entirety:

while True:
    print("Enter 'a' to add two numbers")
    print("Enter 's' to subtract two numbers")
    print("Enter 'm' to multiply two numbers")
    print("Enter 'd' to divide two numbers")
    print("Enter 'q' to quit the program")

    response = str(input('Select an option: ')).lower()

    if response == 'q':
        break
    elif len(response) > 1 or response not in 'asmd':
        print('*Unknown input*\n')
        continue

    while True:
        try:
            num1 = float(input('\nEnter a number: '))
            break
        except(TypeError, ValueError):
            print('*(Input Error) Enter valid number*')
            continue

    while True:
        try:
            num2 = float(input('\nEnter another number: '))
            break
        except(TypeError, ValueError):
            print('*(Input Error) Enter valid number*')
            continue

    if response == 'a':
        result = num1 + num2

    elif response == 's':
        result = num1 - num2

    elif response == 'm':
        result = num1 * num2

    elif response == 'd':
        result = num1 / num2

    print('\nThe answer is ' + str(result) + '\n')
    print('------------------\n')


I think you need to read up a little on namespaces. Both of your namespaces don't make sense unless you will have multiple types of countries and directories.

Your namespace should be if you will have multiple countries

namespace Site.Models.Countries

otherwise it should be

namespace Site.Models

In regards to naming your view models, I would think on how you will use these models in future. If you are likely to have a page for creating, updating, removing and viewing the country, then you might well have the following view models:

DisplayCountry
UpdateCountry
RemoveCountry
SaveCountry

Some people choose to reuse single country model, but I've seen this cause more trouble than benefit. For example, in the RemoveCountry model I'll have only two properties:

public int Id { get; set; }
public string Name { get; set;

The first property is purely for data removal purposes - I assume that you'll pass id to your data layer eventually. Second property is mainly for better UX journey. You might use it for notifying user that they are about to remove a country. E.g., in your view you might have

Warning

Are you sure you want to remove @Model.Name


Here are some suggestions for how you might improve your code.

Use the appropriate #includes

This program fragment requires headers, which should be included:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

Use const where practical

Because the validate_path function does not alter the passed string, the parameter should be declared const:

char *validate_path ( const char* path )

Don't make pointless copies of variables

When you pass a parameter to a function, it's a copy, so there's no reason for this line:

char* path_copy = path;

Just use path directly.

Check for NULL before dereferencing

The first thing the validate_path does is to pass path to strlen, but this results in undefined behavior if path isn't a '\0'-terminated string.  A simple safety check would be to check to see if it's a NULL pointer and exit if it is.

Consider a change to the interface

Instead of allocating memory within the function, consider instead altering the function so that it is passed an input and output buffer.  This way, the code would not need to allocate memory and the caller would do both allocation and freeing.  That makes for a more robust interface and it makes your code simpler.

Prefer for to while

The while loop within the code would likely be more succinctly expressed as a for loop.  That way it's easier to see what is being iterated through and how.

Use a more accurate function name

I would expect that validate_path would do just that and validate a path, but that's not really what's happening here.  Instead, it seems that a more accurate function name would be something like remove_dup_slashes.

Simplify your code

Here's an alternative implementation that uses these suggestions:

char *validate_path(const char *path, char *curr) {
    if (path == NULL || curr == NULL) {
        return NULL;
    }
    char *begin = curr;
    // always copy first character
    *curr = *path;
    // if it's just a single `NUL`, we're done
    if (*curr == '\0') {
        return curr;
    }
    for (path++; *path; ++path) {
        // path points to next char to read
        // curr points to last written
        if (*curr != *path || (*curr != '\\' && *curr != '/')) {
            // only copy if not duplicate slash
            *(++curr) = *path;
        }
    }
    *curr = '\0';  // terminate string
    return begin;
}

Note that the interface is still not a very good one.  It could be improved by also passing in the length of the output buffer and maybe the length of the input buffer as well.


What's most important, as @ChrisW wrote, you need two separate actions for Execute/Redo and Undo. A common command interface would be something like:

public interface ICommand
{
    // Executes this command.
    void Execute();

    // Undoes this command.
    void Undo();
}

The UndoManager should not be generic nor abstract. By making it generic, you only allow it to store a limited set of commands, which is unnecessary. The manager should not know anything about the command it stores, apart from the fact that it can invoke Execute and Undo on them.
There is no need to make it abstract, either. I would however extract its interface so that you can test it (mock it), or provide dummy implementations in special cases. I doubt you would have additional derived undo managers, since its behavior is well defined, so I would probably limit the interface to something like:

public interface IUndoManager
{
    // Executes the specified commmand and adds it to the Undo stack.
    void Execute(ICommand commmand);

    // Undoes the last command in the Undo stack.
    void Undo();

    // Redoes the last command in the Redo stack.
    void Redo();
}

If you want to let your callers know more about the command manager state, then you can extend the whole thing by adding properties like Name to the ICommand, or CanUndo/CanRedo to the ICommandManager. That will allow your callers (i.e. a menu item in your Edit menu) to know if there exists an undoable command, and what's its description. But at all costs avoid exposing "internal" stuff, like the size of your stack.
Although I understand it's conceptual code, I would avoid prefix class names and property names with My (MyClass, MyUndoOperations). It doesn't provide any useful information.


Best practice for asserting a positive IF condition

You should NEVER! add superfluous or unused code.

Your code should have the single if statement checking for not equal.

    const href = element.getAttribute('href');
    if (href.indexOf('#') !== 0) {
        element.setAttribute('target', '_blank');
    }

or better yet avoid the overly complex referencing via get set attribute, and not using a search to find a known location state the whole thing becomes.

    if (element.href[0] === "#") { element.target = "_blank" }

And as a whole there is a huge amount of noise that can be removed

dom.window.document.querySelectorAll("a")
   .forEach(el => el.href[0] === "#" && (el.target = "_blank"));


Fixing minor errors

There are 2 minor errors you should fix and they are related to the commands to type:

print ('=================================================================')
print ('rth_dir ---> Return To Home by direct path')
print ('rth_log ---> Return To Home by logged data')
print ('a ---> imediatly returns to home medium speed: EMERGENCY ONLY')
print ('get log ---> prints all travel log since home point')
print ('=================================================================')

Actually typing rth_dir and rth_log lead to errors. What you actually meant was rth dir and rth log respectively (removed the underscore).

Handling the keyboard interrupt exception

When the user aims to exit your application and presses Ctrl + C, this exception is thrown but not handled:

    ...
    trans_com_in = input('COMMAND COM: ')
KeyboardInterrupt

You can handle the KeyboardInterrupt exception by running a sys.exit() this way:

def trans_com():
    try:
        # The previous function body here
    except KeyboardInterrupt:
       sys.exit()

Better command line approach

You can make your code much cleaner and more efficient if you rely on a parser for command-line options such as the one that comes with Python itself and called argparse. With that in mind, your in addition to cleanness and efficiency of the code mentioned before, this module will help you to get rid of several other lines of code. I

What I mean is that you can substitute these lines:

elif trans_com_in == 'coms':
    print ('=================================================================')
    print ('rth_dir ---> Return To Home by direct path')
    print ('rth_log ---> Return To Home by logged data')
    print ('a ---> imediatly returns to home medium speed: EMERGENCY ONLY!')
    print ('get log ---> prints all travel log since home point')
    print ('=================================================================')
    print ('')
    return trans_com()

  else:
    print ('Unknown command, type "coms" for list of all commands')
    print ('')
    return trans_com()

by using argparse accordingly; for example:

import argparse
# ...
# ...
parser = argparse.ArgumentParser(description="Prototype for sending commands to an Arduino Uno.")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--rth dir", help="Return To Home by direct path.")
group.add_argument("--rth log", help="Return To Home by logged data.")
group.add_argument("--a", help="Imediatly returns to home medium speed: EMERGENCY ONLY!")
group.add_argument("-- get log", help="Prints all travel log since home point.")
args = parser.parse_args()

This approach will  automatically lead several other lines of your code , such as these  ones, to be useless:

else:
    print ('Unknown command, type "coms" for list of all commands')
    print ('')

and:

trans_com_in = input('COMMAND COM: ')

Because when the user tries to run your code this way: python3 solution.py, the Python interpreter will trigger this exception that is self expressing:
    python3 solution.py
    usage: solution.py [-h]
                       (--rth dir RTH DIR | --rth log RTH LOG | --a A | -- get log  GET LOG)
    solution.py: error: one of the arguments --rth dir --rth log --a -- get log is required

By typing the --help (or -h) option, the user can see the information you already wanted to display in your current code:

python3 solution.py -h
usage: solution.py [-h]
                   (--rth dir RTH DIR | --rth log RTH LOG | --a A | -- get log  GET LOG)

Prototype for sending commands to an Arduino Uno.

optional arguments:
  -h, --help           show this help message and exit
  --rth dir RTH DIR    Return To Home by direct path.
  --rth log RTH LOG    Return To Home by logged data.
  --a A                Imediatly returns to home medium speed: EMERGENCY ONLY!
  -- get log  GET LOG  Prints all travel log since home point.

Now with this approach, you need to change your code accordingly, and I think that will be easy for you to do by checking the content of args variable instead of that of trans_com_in.

Other notes

You can type:

print ('PROTOTYPE COMMAND PROMPT FOR TRANS COM\n')

instead of:

print ('PROTOTYPE COMMAND PROMPT FOR TRANS COM')
print ('')

Choose better names: Functions' names like rth_dir(), trans_com() and log_dir() do not tell much about their purpose unless the maintainer of your code digs into their bodies. You should choose names that express right away the purpose of those functions. The same observation is valid when it comes to other variables (such as trans_com_in, r_time, l_time, left, right.
Leave only one blank line between the definitions of your functions. Please check PEP8 for more details.


To construct a pyramid with uses of alphabets. Would you propose any better solution?

General Observations
The code works as long as the user puts in correct limited values.
The indentation is a little off.
You can decrease the vertical spacing quite a bit, most of the blank lines aren't necessary.
Answers

Will I face any problem for some conditions?

If a user enters a negative number or a number greater than 100 this program will have problems with indexing. Always check user input for correctness and possible error conditions. The program will actually have problems if a user enters a number greater than 52 because there are only 26 letters in the alphabet.

How can I simplify my solution?.

You could break the program up into functions, it's not quite necessary with a program this simple, but it is getting close. Two obviously separate functions that could be implemented right now are get_and_validate_user_input() and print_pyramid(). While functions might seem to make the program more complex and longer each function would be a simpler implementation and building block of the overall implementation.

Is it possible to solve this problem without using an array? Then what will be the strategy?.

Yes. It would be possible to treat the numbers as a value in a range between 'A' and 'Z'.
One Declaration Per Line
This line in the code could cause problems in maintenance in a larger program
int space,num_of_rows,p=1,t=0;

Break it up into 3 lines and always initialize variables in C.
int space = 0;
int num_of_rows = 0;
int p = 1;
int t = 0;


The overall quality of your code is very good. It is, at least in my opinion, perfectly fine to have an enum containing the strategy implementations.

A few comments and suggestions though:

private Object concreteStrategy; in your enum can and should be private IInteractionStrategy concreteStrategy; instead. No need to use Object references at all in your enum when you can use IInteractionStrategy instead. By doing this, you won't have to typecast in your setStrategy method.
After implementing the above, private IInteractionStrategy concreteStrategy can and should be marked final.
Even though it's fine to store all your strategies in your enum, you shouldn't enforce it. By having the method public void setStrategy(ConcreteStrategies concreteStrategy) you deny any strategies that are not part of your enum. Either change this method, or add a new one, to be public void setStrategy(IInteractionStrategy concreteStrategy)
IntroductionContext could include a executeStrategy(IInteractionStrategy) method to execute a specific strategy. Then you don't need to first call setStrategy and then call executeStrategy (This is only a suggestion, use it if you like)


Don't know what happens in your db, but LIMIT 1 suggests that result of your query will return exactly what you ask or nothing. In this case no need to compare caller and opponent in if statement - just return (false) from method when $last is empty/false.

Otherwise if one caller may have more 'winner = 0' opponents LIMIT 1 could give you result that you won't use (if statement will reject it) while there's a valid one but was cut off by limit. In this case better provide full description in where clause (if statement will also check if there is any result).


Multidimensional Array indexed by integer array

You don't need to call pow() and calculate powers "from scratch" within each loop iteration - it's probably cheaper to multiply the value calculated during previous iteration as you are calculating consecutive powers of each_size:

size_t temp = 1;
for (const size_t& i : indices)
{
    temp *= each_size;
    index += i * temp;
}

Maybe also come up with a better name for this temp variable than I did ;p

std::nearbyint() is also redunant since you are calculating integral powers of an integer, so your result is going to be an integer by definition.

Apart from this, if your array is really huge, consider using some other container that doesn't store data contiguously as with the fragmented memory there is a risk of not being able to allocate space for such a large object. std::deque might fit your needs, but it's certainly less efficient, so you have to weigh pros and cons. Another advantage would be dynamic size that adds more flexibility to the way your array is used (you can also get it with std::vector, but it's also a contiguous container).

Last but not least, there is no advantage to passing primitive types such as size_t by reference as the associated pointer that's copied is of similar size to the variable that would be copied by value.


This looks similar to the VueJS documentation Tree View example but it is different because of the unique selected aspect.

I would recommend not modifying the class names of elements based on the id, but instead use class bindings. So for the <node>:

What is selectedId? If you look at the example below, you will see I added a property to the <tree> and <node> components, and set that to a new item in the data of the root app.

var app = new Vue({
  el: "#app",
  data: {
    nodes: [/*...*/],
    selectedId: ''
  },
  methods: {
    setSelectedId: function(selectedId) {
      this.selectedId = selectedId;
    }
  }
});

Originally I was going to add properties to both the <tree> and <node> components and use traditional parent-child communication techniques but it got a little cumbersome with emitting from the nested children. Then I decided to use an Event bus to set the selected id (see Non Parent-Child Communication). One could use $root from the <node> component and call the method directly but some believe that goes against the traditional parent-child communication flow.

Also notice the code below uses the shorthand syntax for v-bind.

var selectedNode;
var bus = new Vue();
Vue.component("tree", {
  template: `

       <node
          :node="typeof node === 'string' ? node : Object.keys(node)[0]"
          :nestingTree="typeof node === 'string' ? undefined : Object.values(node)[0]"
          :id="index + '/' + (nestingLevel || 0)"
          :nestingLevel="nestingLevel || 0"
          :selected-id="selectedId"

        ></node>

  `,
  props: ["nodes", "nestingLevel", "selectedId"],
});
Vue.component("node", {
  template: `

        {{node}} {{
          nestingTree
            ? open ? "[-]" : "[+]"
            : ""}}

      <tree v-if="nestingTree && open" :nodes="nestingTree" :nestingLevel="nestingLevel + 1" :selected-id="selectedId" ></tree>

  `,
  props: ["node", "nestingTree", "nestingLevel", "id", "selectedId"],
  data: function() {
    return {
      open: false
    }
  },
  methods: {
    onClick: function(event) {
      this.toggleOpenClosedState(event);
      bus.$emit('setSelectedId', this.id);
    },
    toggleOpenClosedState: function(event) {
      this.open = !this.open;
    }
  }
});
var app = new Vue({
  el: "#app",
  data: {
    nodes: [
      "dfadsfa",
      "fkjsdafkj", {
        carrots: [
          "caveats", {
            moreNesting: [
              "bwah bwah bwah"
            ]
          }
        ]
      }
    ],
    selectedId: ''
  },
  mounted: function() {
      bus.$on('setSelectedId', this.setSelectedId);
  },
  methods: {
    setSelectedId: function(selectedId) {
      this.selectedId = selectedId;
    }
  }
});
.selected {
  font-weight: bold;
}

  <tree :nodes="nodes" :selected-id="selectedId"></tree>


Quickly applying gravity force between bodies

Forward note: To benchmark I simply commented out //self.addCollision(bodyA, bodyB); in step(). Referencing your github code.

To optimize just this method without looking at anything else we can do the
following. This gives a physics workload at ~22ms compared with the original ~27ms on my system.

applyGravityBetween(bodyA, bodyB, collisionCallback) {

    var dx = bodyB.x - bodyA.x,
    dy = bodyB.y - bodyA.y,
    r  = (bodyA.radius + bodyB.radius);

    if ( ( ( dx > r || -dx > r ) || ( dy > r || -dy > r ) ) || ( dx * dx + dy * dy > r * r ) ) {

            r = Math.sqrt(dx * dx + dy * dy);

            if( bodyB.mass == bodyA.mass ){

                r = bodyA.mass / (r * r * r);

                bodyA.vx += r * dx;
                bodyB.vx -= r * dx;

                bodyB.vy -= r * dy;
                bodyA.vy += r * dy;

            }else{

                r = 1 / (r * r * r);

                bodyA.vx += bodyB.mass * r * dx;
                bodyB.vx -= bodyA.mass * r * dx;

                bodyB.vy -= bodyA.mass * r * dy;
                bodyA.vy += bodyB.mass * r * dy;
            }

    } else if( typeof collisionCallback === "function") collisionCallback(bodyA, bodyB);

}

The above code improves by doing the following.

simple bounding box collision check before using a more intensive distance check
remove setting of variables as much as possible, i found in practice this is worth 2 or 3 multiplications in terms of cost. sometimes it's better to repeat the calculations.
Use a comparison of the masses to speed up similar calculations - this is slightly faster where everything starts off with the same mass and could be useful for high N and similar mass simulations, otherwise I would take it out.

Areas for improvement;

This is not coded up but it is common in n-body simulations to group and approximate close,similar & far away masses by grouping them together as one. This can really help as N gets larger because it grows really fast.

2. Reduce Callbacks.

You only asked to optimise the gravity function so this is just an extra.. If you put the following directly into your step() method you can instantly double the speed of the simulation. I found a physics time of 8.8 ms on average - Incorporating all improvements that's almost a third of the original time.

    var i1, i2, bodyA, bodyB, dx, dy, r;

    for (i1 = 0; i1 < this.dynamicBodies.length; ++i1) {
        bodyA = this.dynamicBodies[i1];

        for (i2 = i1 + 1; i2 < this.dynamicBodies.length; ++i2) {
            bodyB = this.dynamicBodies[i2];

            dx = bodyB.x - bodyA.x;
            dy = bodyB.y - bodyA.y;
            r  = (bodyA.radius + bodyB.radius);

            if ( ( ( dx > r || -dx > r ) || ( dy > r || -dy > r ) ) || ( dx * dx + dy * dy > r * r ) ) {

                    r = Math.sqrt(dx * dx + dy * dy);

                    if( bodyB.mass == bodyA.mass ){

                        bodyA.vx += (r = bodyA.mass / (r * r * r)) * dx;
                        bodyB.vx -= r * dx;

                        bodyB.vy -= r * dy;
                        bodyA.vy += r * dy;

                    }else{

                        bodyA.vx += bodyB.mass * (r = 1 / (r * r * r)) * dx;
                        bodyB.vx -= bodyA.mass * r * dx;

                        bodyB.vy -= bodyA.mass * r * dy;
                        bodyA.vy += bodyB.mass * r * dy;
                    }

            } else {
                //this.addCollision(bodyA, bodyB);
            }

        }
    }


Adding and removing PHP parameters on click

First off, you have a couple of bugs:

You can keep clicking the #alphabetical or #builtfilter buttons, and each time you do, it'll add the parameter. Even if it's already there. Yet the "reverse" buttons only replace/remove 1 instance. So if you have:

 /some/path?foo=bar

and click the alphabetical button again a couple of times, you get

 /some/path?foo=bar&sort=alphabetical&sort=alphabetical&sort=alphabetical

But you'll have to click #chronological an equal number of times, to "reset" everything, since only one &sort=alphabetical chunk is removed each time.

Secondly, I don't know the URL you're manipulating, but if there are no parameters to begin with, you end up with an invalid URL like:

/some/path&sort=alphabetical

Note that there's no ? to separate the query string from the path. Instead the & has ended up there - where it shouldn't be.

Also, if you URL has a fragment like #something, you'll be adding paramters after that, which won't work right. Like:

/some/path?foo=bar#fragment&sort=alphabetical

So first off, I'd recommend using jQuery's param method to create a well-formatted query string from an object:

var params = { sort: "", status: "built" }; // an example
var queryString = jQuery.param(params); //=> "sort=&status=built"

Secondly, you can use data-* attributes on your links to specify their action and classes to allow you to find all the links/buttons in one go (here's a related answer of mine).

For instance (simple example):

<button type="button" class="param" data-key="sort" data-value="alphabetical">Sort alphabetically</button>
<button type="button" class="param" data-key="sort" data-value="">Sort chronologically</button>

$(function () { // equivalent to $(document).ready(...)
  var params = { sort: "", status: "" }; // default params

  $(".param").on("click", function () {
    var $this = $(this),
        key = $this.data("param"),
        value = $this.data("value"),
        queryString;

    params[key] = value;
    queryString = jQuery.param(params);

    $(".subsection").attr("href", function () {
      // add or replace the query string as needed
      return this.href.replace(/(\?.*)?$/, "?" + queryString);
    });
  });
});

Note that this doesn't preserve fragments or any parameters that were already in the href, but not in the params object - but I'll leave that as an exercise.


There's an existing technique which is not dissimilar referred to as "exception vomiting". Observe:

void f(void(*p)()) {
    p();
}
template<typename F> void real_f(F func) {
    try {
        throw func;
    } catch(...) {
        f([] {
            try {
                throw;
            } catch(F func) {
                func();
            }
        });
    }
}

This abuses the fact that the compiler must provide a thread-local stack for complex objects for use as exception storage, regardless of their support for other thread local features, and therefore enjoys much broad compiler support. The most obvious drawbacks are a) it's horrible, and b) it's limited to stack semantics.

You could consider a less terrible version as follows assuming the relevant compiler support:

template<typename F> void real_f(F func) {
    thread_local std::vector<std::function<void()>> funcs;
    funcs.push_back(func);
    f([] { funcs.back()(); });
    funcs.pop_back();
}

Your cify function is nothing more than real_f as posted here, but a bit more generic and a lot less reliable as you can't handle multiple instances properly even with the use of __COUNTER__.

The general case cannot be solved without the use of a JIT to create new functions at runtime.


The first thing I can see that should be changed is to add some checks before/after removing files.  As it is currently written, the script will break if it goes to remove a file that isn't there.  So, for instance, if the uninstall is interrupted halfway (computer unplugged, process killed, whatever), then a subsequent run of the script will throw an error and the last part of the script will never be executed.

For simple checks like these, and for that matter for the single-command if checks you already have, you should just use && and || instead.

if [ ${uninstallPdfkit} = "y" ];
then
    pip uninstall pdfkit
fi

and

[ ${uninstallPdfkit} = "y" ] && pip uninstall pdfkit

are exactly equivalent.  Funny thing in this example is that the braces {} are completely unnecessary, as are the double quotes around y, but there should be doublequotes around the variable for safety:

[ "$uninstallPdfkit" = y ] && pip uninstall pdfkit

So instead of:

rm -rf ~/.eesubmit/
echo "The source code and username file for eesubmit has been removed

You should use:

[ -e ~/.eesubmit ] && rm -rf ~/.eesubmit && echo 'The source code and username file for eesubmit has been removed'

This is just scratching the surface; here are some other partial thoughts that could be expanded into further detail:

Why do you echo "Uninstallation complete" if the user decides not to uninstall?
read has a bunch of flags that would be useful; in particular -p to specify a prompt message.  (Use quotes!)
Your big error message has only the first line redirected to stderr.  Consider using single quotes (since you don't need variable expansion) and just have it include multiple lines with one echo command, then redirect to stderr only once for all of it.
You say a shortcut is being created, but you used cp instead of ln -s target linkname.  Also you shouldn't need to use sudo at all.

Hope this helps.


Using functions to separate code for Fahrenheit to celsius conversion

In a more complex program I would probably extract the loop, but I think this is actually pretty good as is. Your main routine reads very well and describes precisely what this program does. You separated the concerns of performing the conversion and displaying the results and your conversion method performs a single task. I agree that extracting it was a wise choice.

You'll often hear the phrase

  A method should do one thing, and do it well.

You nailed the first part, but I'm not so sure about the second. I guess it depends on how accurate you need it to be.

  int celsius = 5 * (fahr-32) / 9;

This is very likely to be a non-integer number before you cast it. C casts from floating point to integer via truncation. This means that you're always "rounding" the result down. I doubt that's what you intended. Use the round() method instead for a more accurate result. Or, even better, return a double.

One other thing, don't abbreviate variable names. I understand why you used fahr instead of fahrenheit, but it's a bad habit to get into.


Finding the minimum ratio out of many lines of input

I guess my comment really was an answer in a philosophical way.  So here is the answer:

Use names for your variables that have meaning.

There are lots of advantages to naming your variables well.  Many people have looked at this question only with a very abstract idea of what you are trying to do.  This makes it difficult to find improvements.  If people know exactly what you are trying to do then they can work out clever ways to achieve that.

As palacsint said: 'It won't be any slower if you use longer and readable variable names' but it may well be faster when people understand it and can see how to improve it.


Is 'try / finally' the best way for me to handle (and close) this long-running IMAP4 connection?

Move the working logic into its own function

def process_mailbox(mailbox):
    user = getpass.getuser() + '@mymailbox.com'
    try:
        mailbox.login(user, getpass.getpass())
    except imaplib.IMAP4.error:
        raise RuntimeError('Credential error.')
    mailbox.select('my_mailbox')
    #whatever else

def main():
    mailbox = imaplib.IMAP4_SSL('mymailbox.com', 993)
    try:
        process_mailbox(mailbox)
    finally:
        try:
            mailbox.close()    # which also expunges the mailbox
        except:
            pass
        mailbox.logout()


scoped_ptr for C++/CLI (ensure managed object properly frees owned native object)

I have only superficially tested the code so far, but it seems to make sense. However, there are some details where I'm either missing something (which wouldn't surprise me, I'm more at home with C#) or the code is more complex than it needs to be. Any comments are appreciated!

The private copy constructors and assignment operators throw exceptions although they can never be called. Wouldn't it suffice to leave them empty?
The constructor and assignment operator both accept not only arguments of type T*, but also exist in a templated version taking U*. I can't quite figure out why. My first thought was that this allows pointers to derived types to be passed; but then again, this is also possible using just the first form.
Similarly, I don't understand the role of the template versions of the private constructor and assignment operator. From my understanding, neither of these will be auto-generated if you don't provide private versions.
The safe bool pattern sound like a great idea (I first had to research it). However, VS2010 shows a compile error saying "cannot convert from 'clr_scoped_ptr<T>::operator safe_bool *::safe_bool *' to 'safe_bool *'". Apparently, it treats the two occurrences of struct safe_bool as two different types. Am I missing something here?
You end the private methods and operators with a semicolon and you write empty argument lists as (void) rather than (). Are these just stylistic choices, or are there advantages in doing this?


Why do you have m_parent? I don't think there are any reasonable operations on a trie that require a parent pointer in each node, and removing it can reduce the space used a lot.

I don't love using a depth argument in add. I'd use the following instead:

void add(const std::string& key, const T& value) {
  return add(key.data(), key.size(), value);
}
void add(const char *key, const T& value) {
  return add(key, std::strlen(key), value);
}
void add(const char* key, std::size_t len, const T& value);  // impl below

I suggest that you keep the children sorted by m_key. Write a comparison functor like so:

struct KeyLessThan {
  bool operator()(const PrefixTree& l, const PrefixTree& r) const {
    return l.m_key < r.m_key;
  }
  bool operator()(const PrefixTree& tree, char c) const {
    return l.m_key < c;
  }
};

Now you can rewrite add like this (using the signature above):

void PrefixTree::add(const char* key, std::size_t len, const T& value) {
  assert(len >= 0);
  if (len == 0) {
    m_value = value;
    return;
  }
  auto it = std::lower_bound(begin(m_branches), end(m_branches),
                             *key, KeyLessThan());
  if (it == end || it->m_key != *key) {
    it = m_branches.emplace(it, *key);
  }
  it->add(key + 1, len - 1, value);
}

The size of m_branches is bounded to be quite small (256 elements in theory; in practice if you're doing English words only it'll be 26 or 52 at the root and much smaller in interior nodes), so this should be quite fast, and it'll make find faster.

Speaking of m_branches, m_children would be a more usual name for it.

It's not really clear that you want find to return a T*; it's odd to give out handles to internal memory in a data structure like this. I would make the signature one of

const T* find(const std::string& key) const
std::pair<bool, const T&> find(const std::string& key) const

or

std::pair<bool, T> find(const std::string& key) const

(if you have access to a C++14 implementation, even better is

std::optional<T> find(const std::string& key) const

Whichever you choose, use the same overloads as with add for const char *, etc.

It is very weird to me to see an #include that's not at the top of the file, and to see printfs in the middle of a C++ file.


Immutable pure data classes with public setters on properties

This is what I program when I want "immutable" classes in C#. You do have an access leak right now though, in that PopularClasses and UnpopularClasses both set and get the underlying object, allowing modification of that object, thus making the class immutable. (This is a bigger problem for set than get, as get would require figuring out which collection type is actually being held. Set you already know because you set it.)

List<string> popularClasses = new List<string>;
popularClasses.add("hello");

pscos = new PopularitySplitClassOptionSet(..., popularClasses, ...);
popularClasses.add("sup"); // This is now added to pscos.

List<string> getAlsoLeaks = (List<string>)(pscos.PopularClasses);
getAlsoLeaks.add("yo"); // This is also added.

You will need to copy on get and set to avoid this. Usually I use LinkedList<T> for this purpose, unless I will need random access, in which case I use List<T>. Since you're only currently using IEnumerable<T>, I'm assuming that random access isn't an issue and using LinkedList<T>.

private LinkedList<ClassOption> popularClasses;
public IEnumerable<ClassOption> PopularClasses
{
    get
    {
        foreach (ClassOption classOption in list.popularClasses)
            yield return classOption;
        // OR:
        // return new LinkedList<ClassOption>(this.popularClasses);
    }
    set
    {
        this.popularClasses = new LinkedList<ClassOption>(value);
    }
}


Transform a List of objects to a string of unique values for use in an SQL query

Creating query (alternative)

Creating SQL like that is vulnerable to SQL Injection. You should use parameters instead.

Here's an example:

using (var cmd = new SqlCommand())
{
    var methods = results
        .SelectMany(x => x.Method?.Split(
            new[] { ':' },
            StringSplitOptions.RemoveEmptyEntries) ?? new string[0]
        ).Distinct();

    var methodParameterNames = new List<string>();
    foreach (var method in methods)
    {
        methodParameterNames.Add($"@Method{methodParameterNames.Count + 1}");
        cmd.Parameters.Add($"@Method{methodParameterNames.Count}", SqlDbType.NVarChar).Value = result;
    }
    var methodParameterString = string.Join(", ", methodParameterNames);

    // build the rest of the query
}

Extracting methods

To extract all methods use the SelectMany extension with the coalescing operator ?? so that you don't have to check for null later. You use an empty collection. The loop simply won't execute. Finally you get unique methods with Distinct.

Creating SQLParameters

In order to create a query for each result you create a SqlCommand. You add each method to a list with parameter names and at the same time add the parameters and the values to the command. The parameters have counters. The first counter needs to be +1 because it is just going to be added and it has to match the counter in the parameter line. At the end you build a string with parameter names that you can use to build the final query.

Example methodParameterString:

 @Method1, @Method2, @Method3

The query to create:

 var sql = $".. WHERE [Method] IN ({methodParameterString}) ..";

Review

string.Join(",", [...].ToArray());

There's no need to .ToArray() the collection for string.Join because it expects an IEnumerable<T>. Calling ToArray you loop over the collection twice.

const string separator = ":";
separator[0]

You can make the separator a char and drop the [0] which is very confusing.

.Where(x => x.Method?.Length > 0)

It's easier to do:

.Where(x => !string.IsNullOrEmpty(x.Method))