It's hard to say exactly how this will be implemented without seeing the entire sub/function, but what you need is a Select Case statement and a For loop.

Pseudo code to get you started:

    Dim row as Long
    For row = 1 to 24
        Populate row
    next row

End Sub

Private Sub Populate(ByVal row as Long)
     Dim text as string
     text = GetText(row)
     Dim value as Variant
     value =  GetValue(row, text)

     Sheets("Groups").Cells(row,1) = text
     Sheets("Groups").Cells(row,2) = value
End Sub

Private Function GetText(ByVal row as Long) As String
    Select Case Row
        Case 1: GetText = "Groups"
        Case 2: GetText = "9N4"
        Case 3: GetText = "1A2A"

        'etc

     End Select
End Function

Private Function GetValue(ByVal row as Long, ByVal matchText as String) As Variant
    If row = 1 Then
        GetValue = "Aantal"
    Else
        GetValue = Application.WorksheetFunction.CountIf(Sheets("totallist").Range("G2:G" & rn_totallist), matchText)
    End If
End Function


What you need is an ADODB.Command. It's the same query with different parameters, so you should use a parameterized query. Honestly, you should be using a parameterized query anyway. You have no idea what the user has put into those cells. This is a SQL Injection disaster waiting to happen. Let's say I put '; DROP DATABASE trackerfy2015 -- into cell E6. Boom. There goes your entire database. Poof. Gone. Up in smoke.

xkcd: Exploits of a Mom

So, about that parameterized query..

Dim cmd as New ADODB.Command

Const sql As String = & _
    "SELECT sum(Hours)/80 " & _
    "FROM payroll2015_rif " & _
    "WHERE DepartmentCode = ? " & _
        "AND payperiod = ? " & _
        "AND paycode IN ('REG1', 'REG2');"

With cmd
    .CommandType = adCmdText
    .CommandText = sql
    .ActiveConnection = conn

    .Parameters.Append .CreateParameter(Name, Type, adParamInput, Size, Range("$E$6").Value)
    .Parameters.Append .CreateParameter(Name, Type, adParamInput, Size, Range("C20").Value)

    Set rs = .Execute
End With

' Transfer Result
Sheets(2).Range("$H20").CopyFromRecordset rs

' reset the value of the second parameter
cmd.Parameters(1).Value = Range("C21")

Set rs = cmd.Execute

Note that I didn't set all of the parameters for the CreateParameter function because I have no way of knowing the appropriate values.

I need to mention something that you did very very right. Using Worksheet.CopyFromRecordSet is by and far the most efficient way to transfer data from a Recordset to a worksheet. Well done. You have no idea how often I see people loop through a recordset to populate a worksheet. I'm very happy to see you do it the right way.

Some other notes:

You have unused variables wks and xrow. Put the first to good use by setting it to Sheets(2). This way if the destination sheet should ever need to change, you only have to do it in one place. Remove the other dead variable.
Add an error handler so you can make sure the connection and recordset always get closed no matter what happens.


Simplifying exception handling on Enumerators

I would use Linq methods to simplify the code. Also I've extracted 2 methods to simplify the main method. And please rename GetFilesWeAreLookingFor to whatever your find appropriate :).

private static IEnumerable<string> GetFilesWeAreLookingFor(string currentDir)
{
    try
    {
        return Directory.EnumerateFiles(currentDir, "*.exe")
            .Where(fileName => fileName.IndexOf("unins", 0, StringComparison.CurrentCultureIgnoreCase) == -1);
    }
    catch (UnauthorizedAccessException uae)
    {
        Debug.WriteLine(uae.Message);
    }
    catch (PathTooLongException ptle)
    {
        Debug.WriteLine(ptle.Message);
    }
    return Enumerable.Empty<string>();
}

private IEnumerable<string> GetNestedFiles(string currentDir, int nestedDepth)
{
    try
    {
        return Directory.EnumerateDirectories(currentDir)
            .SelectMany(subDirectory => SearchSubdirs(subDirectory, nestedDepth));
    }
    catch (UnauthorizedAccessException uae)
    {
        Debug.WriteLine(uae.Message);
    }
    catch (PathTooLongException ptle)
    {
        Debug.WriteLine(ptle.Message);
    }
    return Enumerable.Empty<string>();
}

private IEnumerable<string> SearchSubdirs(string currentDir, int currentDepth)
{
    IEnumerable<string> filesWeAreLookingFor = GetFilesWeAreLookingFor(currentDir);

    if (currentDepth < _maxDepth)
        filesWeAreLookingFor = filesWeAreLookingFor.Concat(GetNestedFiles(currentDir, currentDepth + 1));

    return filesWeAreLookingFor;
}


1) Starting a new thread seems like quite an overhead for this task
  but I don't see an alternative (other than using a 3rd party tool like
  jersey which will presumably do the same thing anyway ?)

I would use there some message processing tool. Send somewhere and than process what should be processed. But it's much more complicated. I would use ExecutorService which is provided by java-8. I think it's old school to create Thread manually for this case.

  2) Should I be doing something more sophisticated than creating a
  local RestTemplate each time ?

You can use @Configuration FactoryBean where you can create one spring @Bean for RestTemplate and inject this instance into your class where is postLog method located.

@Configuration
public class BeansFactory {
 @Bean public RestTemplate restTemplate(){
       return new RestTemplate();
 }
}

and inject in spring @Component

@Autowire private RestTemplate restTemplate;

  3) Is it generally the right approach anyway (it feels over
  simplistic)

From my perspective doing async work for REST with Threads is little bit tricky. And open to few potential problems like - too many Threads, by default all threads with the same priority etc.

I think that for some async tasks the best way is to have publisher-subscriber approach. You are doing something, then you want to run something in the background to avoid waiting for response and return response without already finised async call.

To avoid doing another call you can push somewhere this event and process event somewhere else which is not depended on the current application.

Check also https://spring.io/guides/gs/messaging-reactor/


HTML

I noticed that you didn't put the ul or ol tag in your code, you need to put your li tags inside the a ul or ol in order to have a more semantic structure.

CSS

I did some very basic styling for the modal to look more attractive in the demo.

.modal {
    display: none;
    background: #000;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: .8;
}

.modal .modal-content {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -120px;
    margin-left: -150px;
    color: #fff;
}

.modal img, .modal span {
    z-index: 10;
}

JavaScript

I put all the images inside the images variable and also put the modal element in it's own variable.

Then I looped through each image using the forEach(), defining that for each image, which the user has clicked, it will put a display: block to the modal element and insert a piece of HTML containing an  tag and a  tag with the alt property in it.

And last but not less important, everytime that the user clicks in the modal area with the display: block activated, it will put a display: none automatically on it.

var images = document.querySelectorAll('#my-images img'),
    modal = document.querySelector('.modal');

// Loops through the all the images selected...
images.forEach(function (image) {
    // When the image is clicked...
    image.addEventListener('click', function(event) {
        modal.innerHTML = '

' + event.target.alt + '
';
        modal.style.display = 'block';
    });
});

// When the user clicks somewhere in the "modal" area it automatically closes itself
modal.addEventListener('click', function () {
    this.style.display = 'none';
});

I didn't bother to put any effect on the modal element, I was simply controlling the hide and show properties and didn't cared about fadeIn or fadeOut that were mentioned in your code.

The easiest and fastest way to make some animations, would be making use of some third-party animation library such as Animate.css that comes with tons of cool effects to work with.


Finding the middle day of a month, given any day within that month

Since February is the only month where the middle is 15 you could just write

d.month == 2 ? 15 : 16


Rust: calculating mean, median, and mode for numbers from stdin

Good job! I'm sure there are problems with my take, but, for what it's worth, here's how I might suggest improving things a bit.

use std::collections::HashMap;
use std::io::{self, Write}; // Personal preference, but I prefer avoiding glob imports
use std::num::ParseIntError;

fn main() {
    let stdin = io::stdin();
    let mut stdout = io::stdout();

    // Allocate a String buffer once and keep reusing it, instead of allocating multiple times.
    let mut line = String::new();

    // No need to name the loop since it's the only one. Loop naming
    // isn't very idiomatic in rust; it's typically used only when there
    // are loops within loops and naming is needed to solve ambiguity.
    loop {
        print!("Enter space-separated numbers (q for quit)> ");
        // Unwrap here seems OK, since if flush() fails, something went terribly wrong.
        stdout.flush().unwrap();

        // Clear the String buffer to prepare for reuse.
        line.clear();
        // Unwrap here seems OK, for similar reasoning as above.
        stdin.read_line(&mut line).unwrap();

        if line == "q\n" {
            break;
        }

        // Let the closure passed to map return a Result, then collect into a
        // Result<Vec<_>, ParseIntError>, which will be Ok if all parsing succeeded
        // or Err if any parsing failed. After that, match on your Result to handle errors.
        let mut nums = match line
            .split_whitespace()
            .map(|s| s.parse::<i32>())
            .collect::<Result<Vec<i32>, ParseIntError>>()
        {
            Ok(vec) => {
                if vec.is_empty() {
                    // Error handling: If user didn't give you any input, try again.
                    continue;
                }
                vec
            }
            Err(_) => {
                // Error handling: If user gave you bad input, try again.
                println!("Invalid input. Only integer values are accepted. Please try again.");
                continue;
            }
        };

        // Casting i32 to f32 is fine.
        let mean = nums.iter().sum::<i32>() as f32 / nums.len() as f32;
        let median = get_median(&mut nums);
        let mode = get_mode(&nums);

        println!(
            "numbers: {:?}, mean: {}, median: {}, mode: {:?}",
            &nums, // No need to consume nums (even though in this case you never use it again)
            mean,
            median,
            mode,
        );

        break;
    }
}

// Avoid the clone by passing a mutable reference
fn get_median(vec: &mut Vec<i32>) -> f32 {
    // is_empty() is slightly more idiomtic than vec.len() < 1
    if vec.is_empty() {
        return 0.0;
    }

    vec.sort();

    // * `vec.len() / 2` is reusable code; so make it it's own varible
    // * Instead of using `vec.get(index).unwrap()`, use `vec[index]`,
    //   as we know our index is valid.
    let index = vec.len() / 2;

    if vec.len() % 2 == 1 {
        vec[index] as f32
    } else {
        (vec[index - 1] as f32 + vec[index] as f32) / 2.0
    }
}

// * Whenever you want to pass &Vec<_> as an argument to a function,
//   consider passing &[_] instead. It works with more types.
// * Mode is not necessarily unique; so return a Vec<i32>.
fn get_mode(slice: &[i32]) -> Vec<i32> {
    if slice.is_empty() {
        // bail early if the input is empty; so that we avoid
        // unnecessarily allocating a HashMap.
        return vec![];
    }

    // Waste a little space by allocating from the start a HashMap
    // of maximum possible size; this avoids the possibility of
    // having to rellocate once the size has grown bigger than
    // capacity. It's a micro optimization, but in general in rust
    // if you know how big a heap allocated thing (like Vec, String, HashMap)
    // etc. needs to be in advance; take advantage of that information.
    let mut map = HashMap::with_capacity(slice.len());
    for num in slice {
        let count = map.entry(num).or_insert(0);
        *count += 1;
    }

    // Unwrap is OK because we know the map is non-empty.
    let max_value = map.values().map(|v| *v).max().unwrap();

    // Use into_iter() as we don't need the map anymore and
    // that will more efficiently create the vec than
    // if we had used iter()
    let mut vec = map
        .into_iter()
        .filter_map(|(k, v)| if v == max_value { Some(*k) } else { None })
        .collect::<Vec<i32>>();

    // Sort because it makes the output deterministic
    vec.sort();

    vec
}
```


Creating a List of objects of a particular type only

You can use the LINQ extension method IEnumerable.OfType<TResult>(), it returns any elements matching the type of the specified generic type argument:

var jointLoads = AllLoadCases.OfType<JointsLoadingPattern>();

This will return an IEnumerable<JointsLoadingPattern>, you can always call .ToList() to convert it.

Update

As noted in the comments, since OfType<TResult> uses the is operator internally, it will also return any sub-types of TResult type. If you want to avoid this you can write your own extension method:

public static class Extensions
{
    public static IEnumerable<TResult> OfExactType<T, TResult>(this IEnumerable<T> source)
        where TResult : T
    {
        return OfExactType<TResult>(source);
    }

    public static IEnumerable<TResult> OfExactType<TResult>(this IEnumerable source)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));
        return OfExactTypeImpl<TResult>(source);
    }

    private static IEnumerable<TResult> OfExactTypeImpl<TResult>(IEnumerable source)
    {
        var type = typeof(TResult);
        foreach (var t in source)
        {
            if (t.GetType() == type)
            {
                yield return (TResult)t;
            }
        }
    }
}

Example usage:

AllLoadCases.OfExactType<ILoadPattern, JointsLoadingPattern>();
AllLoadCases.OfExactType<JointsLoadingPattern>();

The main difference between the 2 being, that in 1 case you will get a compile-time error when you attempt to provide invalid types, while in the other case this, will be ignored and it will simply return nothing.


Several observations about the code not necessarily related to the (not so) explicit question:

Formatting

Have some consistent indentation of your code, it will make it much easier to read. Rubberduck is a great tool for that, and it will help you find all sorts of spots for other VBA code improvements. (Happy user, haven't yet contributed to the project.)

Remove excessive vertical spacing as it allows you to fit more of this lengthy procedure on the screen.

Variable Naming

Your first set of variables seem reasonably well named (though I don't speak... whatever language you've named them in :) until... we get to vk - This seems to be the commission percentage so why not call it CommissionPercent?

Your second set of variables, however, leave a bit to be desired in the choice of names.

Drop the Hungarian Notation unless you're going to do it usefully. (Most people don't, so you're not alone!)

FirstRow is just as intuitive a name as lngFirstRow and when you're using it, knowing that it's a Long doesn't add value. This applies to all the lng prefixed variables.

lngCol - when I look at that, I'm going to assume that it's something like "the current column I'm processing", but looking through the code, it's actually a pointer to the Client column, and it never changes, so how about Const CLIENT_COL as Long = 2 instead.

The same can be done with lngKom - make it a Const called I'M_NOT_SURE_COL (Col 11 is col K, but that's a somewhat random column in your "Market" section. Currently only set to "EE", but that could certainly change, I'd think).

Clean up the Select statements

In this code:

Select Case klienta_nr
  Case 111111
  '(Vacija, Francija, Niderlandes, Italija, Irija) - 30 EUR MIN
  If klienta_nr = 111111 And (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then

The If klienta_nr = 111111 And is totally unnecessary. Because you're inside the Select Case and this is Case 111111, klienta_nr will, by definition, be 111111. Remove that part to simplify the code a bit.

Actually, eliminate all the "Magic Numbers" then clean up the Select statements

In your Select you have Case 111111 (6 ones). Inside that Case, you have If 111111 (6 ones), followed by If 111111 (6 ones), followed by If 1111111 (7 ones). This appears, to the innocent bystander, to be a typo on the last If statement. However, since all the rest of the conditions are the same, maybe it's intentional. In either case, it's confusing for the next programmer to come along (where "Next Programmer" is often "Future You"). If you declare some Const ABC_CLIENT_ID as Long = 111111 and Const DEF_CLIENT_ID as Long = 1111111, at least "next programmer" will know that this isn't a typo since you've intentionally declared 2 separate constants for the different values.

Be aware that your code will never fall into the 3rd If statement. By definition, when the code falls into the Case 111111 (6 ones) section of the Select, If klienta_nr = 1111111 (7 ones) will never be True. This is dead code (as written) and should be removed, or the typo fixed to make it do what you intend.

The same can be said for the Case 2222222 (7 twos) section. The only If that will ever execute is the middle one under the 'Set 30 EUR Min comment. The first If only has 6 twos, which will never evaluate to True and the last has only 1 two.

Eliminate GoTo

The good news about that last If statement never executing is that you'll never hit the GoTo AllElseFails jump! If you really need to execute the AllElseFails code at some point in the Case 2222222 section, then refactor your code like this:

Private Sub AllElseFails(ByVal vk As String, ByRef Komisija As Double, ByVal lngCounter As Long, ByVal lngKom As Long, ByVal Summa As Double, ByVal WkSht As Worksheet)

  'IP2, 0.03% komisija, 40 EUR/USD Max
  If Right(vk, 1) = 1 Or Right(vk, 1) = 8 Then
    Komisija = Summa * 0.003
    WkSht.Cells(lngCounter, lngKom) = Komisija
  End If
  'IP1, 0.1% komisija, 40 EUR/USD Max
  If Right(vk, 1) = 7 Then
    Komisija = Summa * 0.01
    WkSht.Cells(lngCounter, lngKom) = Komisija
  End If
  'Komisija MAX is 40, so anything >=40 equals 40
  If Komisija >= 40 Then
    WkSht.Cells(lngCounter, lngKom) = 40
  End If
End Sub

And call AllElseFails when you need that code instead of jumping around in a Select Case structure like this:

      If klienta_nr = 2 And (Left(ISIN, 2) <> "DE" Or Left(ISIN, 2) <> "FR" Or Left(ISIN, 2) <> "NL" Or Left(ISIN, 2) <> "IT" Or Left(ISIN, 2) <> "IE") Then
        AllElseFails vk, Komisija, lngCounter, lngKom, Summa, Worksheet(1)
      End If
    Case Else
      AllElseFails vk, Komisija, lngCounter, lngKom, Summa, Worksheet(1)

That's the way to reuse the code without getting the "next programmer" very confused.

As an added tweak to the refactored Function, you have:

  If Right(vk, 1) = 1 Or Right(vk, 1) = 8 Then

followed by

  If Right(vk, 1) = 7 Then

You should probably change that second If statement to an ElseIf. There's no need to execute the check for 7 if you've already determined it's a 1 or 8.

Refactor to eliminate redundant code:

You have

(Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE")

all over the place. This is a great opportunity to create a Function that does all that testing for you and returns a Boolean:

Private Function IsADesiredISIN(ByVal ISIN As String) As Boolean

    Select Case ISIN
    Case "DE", "FR", "NL", "IT", "IE"
      IsADesiredISIN = True
    Case Else
      IsADesiredISIN = False
    End Select

End Function

Then your if statements become:

If klienta_nr = 111111 And IsADesiredISIN(Left(ISIN, 2)) Then
If klienta_nr = 222222 And IsADesiredISIN(Left(ISIN, 2)) Then

Which should really be

If IsADesiredISIN(Left(ISIN, 2)) Then

since the klienta_nr = 111111 and klienta_nr = 222222 are redundant (as mentioned above).

And, as an added bonus, if you need to include a new country code in the list of ISIN you're processing, you do it in one place and it effects all locations meaning you don't accidentally forget one.

This really hasn't addressed your actual question (I don't think), but it does simplify the code by eliminating some questions that the "next programmer" may have about what the code does and why.


#Importing required librarys

I can see that. Don't comment on what's obvious from the syntax

try:
    import matplotlib.pyplot as plt
except:
    raise

Catching an exception only to rethrow it? That's a waste

import networkx as nx
import csv
import random
import math

def prod(iterable):
    p= 1
    for n in iterable:
        p *= n
    return p

You may want to look at numpy, it has function like this written in efficient C.

def Sum(iterable):
    p= 0

p? why p?

    for n in iterable:
        p += n[3]
    return p

The python style guide recommends lowercase_with_underscores for global function names. The name also suggests its a generic summing function which its not. No indication is given for what kind of data it expects. A docstring should at least explain that.

def CalcTriads(n):
    firstgen=G.neighbors(n)

Don't use global variables. Instead pass G in as a parameter. Also, I recommend against calling it G.

    Edges=[]
    Triads=[]

Python style guide recommemnds lowercase_with_underscores for local variables names

    for i in firstgen:
        Edges.append(G.edges(i))

I recommend a list comprehnsion

Edges = [G.edges(i) for i in firstgen]

    for i in xrange(len(Edges)):

Don't iterate over the integers, iterate over the edges. Use for edge in Edges:

        for j in range(len(Edges[i])):# For node n go through the list of edges (j) for the neighboring nodes (i)

I recommend putting the comment on a seperate line from the if. Otherwise it tends to wrap off the side of the screen and that's annoying. Also, iterate over the container, not the indexes. Use something like for source, dest in edges:

            if set([Edges[i][j][1]]).issubset(firstgen):# If the second node on the edge is also a neighbor of n (its in firstgen) then keep the edge.

Create a list with a single element, putting that in a set, simply to call issubet is silly. Use Edges[i][j][1] in firstgen.

                t=[n,Edges[i][j][0],Edges[i][j][1]]
                t.sort()
                Triads.append(t)# Add found nodes to Triads.

    new_Triads = []# Delete duplicate triads.
    for elem in Triads:
        if elem not in new_Triads:
            new_Triads.append(elem)
    Triads = new_Triads

That is an inefficient way of doing that. Instead, make Triads a set and put tuples rather then lists in it. That'll be faster and easier to read.

    for i in xrange(len(Triads)):# Go through list of all Triads finding the weights of their edges using G[node1][node2]. Multiply the three weights and append value to each triad.

This code would be way cleaner if you used for triad in Triads:

            a=G[Triads[i][0]][Triads[i][1]].values()
            b=G[Triads[i][1]][Triads[i][2]].values()
            c=G[Triads[i][2]][Triads[i][0]].values()
            Q=prod(a+b+c)
            Triads[i].append(Q)

    return Triads

###### Import sorted edge data ######
li=[]

Bad name, gives no idea what it intends

with open('Sorted Data.csv', 'rU') as f:

I think you are supposed to read csv files in a binary mode.

    reader = csv.reader(f)
    for row in reader:
        li.append([float(row[0]),float(row[1]),float(row[2])])

Use for source, dest, value in row: li.append(float(source), float(dest), float(value))

Do you really want floats? Are the source and destination really floats or are they ints?

G=nx.Graph()
G.add_weighted_edges_from(li)

for i in xrange(800000):

Don't execute loop at the module level. Code written inside  a function will run faster.
        e = random.choice(li)   # Choose random edge

    TriNei=[]
    a=CalcTriads(e[0]) # Find triads of first node in the chosen edge

Don't use variable names like a, a one letter variable name is terrible waste of information capacity.

    for i in xrange(0,len(a)):

Don't use xrange to iterate over containers.

        if set([e[1]]).issubset(a[i]): # Keep triads which contain the whole edge (i.e. both nodes on the edge)
            TriNei.append(a[i])
    preH=-Sum(TriNei) # Save the "energy" of all the triads of which the edge is a member

    e[2]=-1*e[2]# Flip the weight of the random edge and create a new graph with the flipped edge
    G.clear()
    G.add_weighted_edges_from(li)

You should be able to find and change the edge weight directly. Reconstructing the whole graph is going to be kinda slow.

    TriNei=[]
    a=CalcTriads(e[0])
    for i in xrange(0,len(a)):
        if set([e[1]]).issubset(a[i]):
            TriNei.append(a[i])
    postH=-Sum(TriNei)# Calculate the post flip "energy".

Seeing the same piece of code in two place is a big hint. Write a function!

    if postH<preH:# If the post flip energy is lower then the pre flip energy keep the change
        continue

    elif random.random() < 0.92: # If the post flip energy is higher then only keep the change with some small probability. (0.92 is an approximate placeholder for exp(-DeltaH)/exp(1) at the moment)
        e[2]=-1*e[2]

What you should consider doing is writing a function which given a node calculates the change in "energy" that would occour if it was flipped. Right now you calculate before and after, but you should be able to simply calculate the delta without changing it. If you can effeciently calculate the delta, that's all you need.


Before addressing efficiency, some improvements I would recommend:

No need for a goto here.  This is easy to turn into a for loop.
Say const char *input2, to avoid accidentally modifying your input string.
Use whitespace to clarify order of operations:

if(sum > n<<2)  Relational operators and shifts are right next to each other on the operator precedence table.
sum += *input2 - '0';

Take out the asterisk in *input2++;  You aren't using the character.

And a more subtle issue:

isdigit expects an unsigned char casted to an int.  char is usually signed (but on some platforms, it's unsigned).  Thus, if one of your input bytes is not ASCII, it may lead to undefined behavior.

isdigit((unsigned char) *input2)

Here is an editorialized version of your code:

void GetCount(const char* input2)
{
    int sum = 0;    /* Sum of digits in current number */
    int n = 0;      /* Number of digits in current number */

    for (;;)
    {
        input2++;
        if (*input2 == '\0')
            break;

        /*
         * If we have a digit, increment sum and n appropriately.
         *
         * Otherwise (we ran into a brace or comma), tally the current number,
         * and clear the stats for the next number.
         */
        if(isdigit((unsigned char) *input2))
        {
            sum += *input2 - '0';
            n++;
        }
        else
        {
            if(sum > n<<2)
                output1++;
            sum = 0;
            n = 0;
        }
    }
}

Let's look at the sum > n<<2 line, which looks wrong to me.  Here's the condition we want to test (simple, but inefficient):

1. (double)sum / n >= 5.0

We can express it in integer arithmetic as:

2. sum >= n * 5

Now I get what you were trying to do.  Your next steps converted the multiplication to a less expensive shift:

3. sum > n * 4
4. sum > n<<2

Step 3 is wrong.  sum can be greater than n * 4 but less than n * 5.  Example:

34566: sum = 24, n = 5

n * 4 = 20      sum >  n * 4 holds
n * 5 = 25      sum >= n * 5 does not hold

The good news is, we can get rid of the multiply and even the shift!  Just increment n by 5 each iteration:

        if(isdigit((unsigned char) *input2))
        {
            sum += *input2 - '0';
            n += 5;
        }
        else
        {
            if(sum >= n)
                output1++;
            sum = 0;
            n = 0;
        }

Finally, let's get rid of that isdigit.  It's probably pretty fast, but it has to guard against EOF and do a table lookup.  Assuming your input is guaranteed to be in the syntax you describe (non-negative integers delimited by commas and wrapped in braces), you can test for two specific characters instead of having to do a character class lookup.

Here is a final version, with more cleanups:

/*
 * Given a list of numbers in the following syntax:
 *
 *     list ::= '{' '}'
              | '{' number (',' number)* '}'
 *
 *     number ::= [0-9]+
 *
 * Count how many numbers have digits that average to 5 or more.
 */
int GetCount(const char* input)
{
    int sum = 0;                /* Sum of digits in current number */
    int length_times_five = 0;  /* Number of digits in current number, times 5 */
    int ret = 0;

    /*
     * Handle empty list.  Otherwise, the following code
     * would return 1 because 0 >= 0.
     */
    if (input[0] == '{' && input[1] == '}')
        return 0;

    while (*++input != '\0')
    {
        if (*input == ',' || *input == '}')
        {
            if(sum >= length_times_five)
                ret++;
            sum = 0;
            length_times_five = 0;
        }
        else
        {
            sum += *input - '0';
            length_times_five += 5;
        }
    }

    return ret;
}


Here's a few things that caught my eye:

I'm assuming this is just a sketch of an unfinished class, or perhaps a learning excersize? As it stands, your class is unnecessary, and I would advise against using it. Since it just wraps a built in int, built in ints might as well be used. Various functionalities could indeed make it a useful class though (for example, arbitrary precision capabilities).
If the constructor's argument can't be used, throw an exception. Objects should never exist in an incomplete or meaningless state. What does a false number mean? What does multiply($n1, $n2) mean if one of the numbers is false? Just throw an exception instead.
I wouldn't bother having Numbers exist. Just have the operations be members of Number. Static methods tend to be regretted down the line. It's always better to have a non-static that could be static than to have a static that you later realize shouldn't be static. Also, having the method be internal to Number would be nice as it would allow you access to Number's internals without having to expose them to the world.
multiply should return a Number, not an int. Why bother abstracting into an object if you're not going to stick with it?
Name your argument to the constructor something meaningful. Rather than $n name it $value (or something along those lines).
Consider expanding your number to handle more than ints. Using the BC Math or GMP extensions, you could write a class that handles arbitrary precision numbers very easily.

I would probably go with BCM just because it's more commonly available. It's statically linked on Windows and thus always enabled, whereas GMP is bundled in the binary archives, but not enabled by default. I'm not sure what the situation is on linux.
Since BCM works with ASCII encoded base 10 numeric strings and GMP works with handles, GMP is probably more memory efficient. No idea about general performance though since I'm not very familiar with GMP or BCM's internals or features.
I belive GMP is limited to integers whereas BC Math is not. That could be good or bad depending on the needs/expectations.

You missed the public in front of your constructor.
Depending on what you end up doing with the class, I probably wouldn't expose the internal representation. For example, if you ended up using GMP and wanted to switch to BMP, you couldn't if you had previously exposed the internals. Rather than expose them directly, I would implement methods like toString, toInt, toFloat, toBinary, etc. Those methods woud then either do the conversion if possible, or, if precision would be lost (like trying to convert a value to large for an int to an int), an exception would be thrown (or you could return false depending on how you expected to use the methods and if you consider a failure to convert a truly exceptional situation).
As it is right now, Number is a misnomer. 5 and 5.0 are both numbers, but your class only supports 5. I might rename it to Integer or something similar.


You're using calc() when there's no need for it because you already know the size of the parent element and you're not mixing units.  You're also not providing a fallback for browsers that don't support calc(), which in turn makes your entire demo appear as though it doesn't work.

.grid-chooser + .grid .row {
    height: 23px;
}
.grid-chooser + .grid .square {
    height: 100%;
    width: 23px;
}

If you want to be able to change the size of your picker without having to recalculate the sizes of the descendant elements, you should be using variables via CSS preprocessors.  In addition to increasing your browser support, you'll also have a marginally smaller file.

You're using display: inline-block here when float: left would be a better choice.  Using negative margins to remove the space between inline elements is not reliable under any circumstance, ever.

.grid-chooser + .grid .square {
    float: left;
    padding: 1px;
}

You can eliminate need for the .inner element using this CSS (you'll need to modify your JS to match):

.grid-chooser + .grid {
    width: 120px;
    height: 120px;
    background: rgba(0, 0, 0, 0.2);
    position: relative;
    padding: 2px;
}
.grid-chooser + .grid .row:first-child .square:first-child {
    background: rgba(0, 0, 0, 0.4);
}
.grid-chooser + .grid .square {
    height: 22px;
    width: 22px;
    float: left;
    margin: 1px 0 0 1px;
    border-radius: 3px;
    background: rgba(0, 0, 0, 0.2);
}
.grid-chooser + .grid .square:hover,
.grid-chooser + .grid .square.highliger {
    background: rgba(0, 0, 0, 0.4)
}


Test whether the edit-distance of two strings is at most 1

It looks like you either imported std::string or the whole standard namespace into the global namespace.
It's ok to do the former in implementation-files, though I would desist as it doesn't gain you all that much in brevity.
If it's the latter, read "Why is “using namespace std;” considered bad practice?" and change it.
Avoid allocating memory. Doing so is slow and can fail. That means accepting the arguments by constant reference, not using temporary copies, and not modifying the arguments.
If you had C++17, it would mean changing to std::string_view for the added flexibility.
Prefer using auto to a more complicated expression using decltype. It's less error-prone, more readable, and also shorter.
<algorithm> contains std::min(). Using that is more readable, shorter and no less efficient than writing it out using the conditional-operator.
Did you test ("abc", "b")? That's two deletions edit-distance, but will be accepted anyway.
Keep your line-length reasonable. Horizontal scrolling kills readability.

Using all that, but staying true to C++11:

#include <string>
#include <algorithm>

bool oneAway(const std::string& a, const std::string& b) noexcept {
    if (a.size() > b.size())
        return oneAway(b, a);
    if (b.size() - a.size() > 1) // No need to look further, pure optimization
        return false;
    auto begin = std::mismatch(a.begin(), a.end(), b.begin());
    using reverse_it = decltype(a.rbegin()); // std::make_reverse_iterator is C++14
    auto end = std::mismatch(a.rbegin(), reverse_it(begin.first), b.rbegin());
    return end.second.base() - begin.second < 2;
}

And for testing:

#include "one_away.h"
#include <iostream>
#include <cstdlib>

static bool do_test(const std::string& a, const std::string& b, bool expected) {
    bool r = oneAway(a, b);
    std::cout << (r == expected ? "[OK] " : "[FAIL] ")
        << std::boolalpha << r << " \"" << a << "\" \"" << b << \"\n";
    return r == expected;
}

static bool test(const std::string& a, const std::string& b = a, bool expected = true) {
    bool r = do_test(a, b, expected);
    if (a != b)
        r &= do_test(b, a, expected);
    return r;
}

int main() {
    bool r = test("");
    r &= test("abc");
    r &= test("pale", "ple");
    r &= test("pales", "pale");
    r &= test("pale", "bale");
    r &= test("pale", "bake", false);
    r &= test("abc", "b", false);
    std::cout << (r ? "[OK]\n" : "[FAIL]\n");
    return r ? 0 : EXIT_FAILURE;
}


Taking memory into consideration:

That code uses \$(n*log(n))\$`sizeof(int)` bytes of heap memory for array elements storage.

This code makes it n `sizeof(int)`. By creating temporary memory only once and passing it to other functions, it saves significant memory in case of large arrays.

/* sorts given input array in ascending order */

void merge_sort (int * arr,int size)
{
    int *temp;
    if((temp = (int*)malloc(sizeof(int)*size))!=NULL)
      msort(arr,temp,0,size-1) ;
}

void msort(int * arr,int * temp,int first,int last)
{
    if (first>= last) return ;

    int split = (first+last) / 2 ;

    msort(arr,temp,first,split) ;
    msort(arr,temp,split+1,last) ;
    merge(arr,temp,first,split,last) ;
}

void merge (int * arr,int *temp,int f_start,int f_end,int s_end)
{
                                /*    s_start == f_end+1      */
    int i = f_start ;
    int j = f_end+1 ;
    int k = f_start ;

    while (i<=f_end && j<=s_end)
    {
        if (arr[i]<arr[j])
            temp[k++] = arr[i++] ;
        else
            temp[k++] = arr[j++] ;
    }

    while (i<=f_end)
            temp[k++] = arr[i++] ;

    while (j<=s_end)
            temp[k++] = arr[j++] ;

    for (i=f_start ; i<=s_end ; i++)
    {
        arr[i] = temp[i] ;
    }
}


Starting with your last question first, I'm surprised that you don't always get a stack overflow. Clojure does not support tail-call elimination, meaning that purely recursive functions (like both your fibs-until and zeckendorf) are likely to blow up the stack.

There are various reasons why this isn't an issue in practice, first and foremost of which are Clojure's lazy sequences.

Elements of a lazy sequence aren't generated until they're used. Among other things, this means that Clojure can easily handle infinite sequences. So a more idiomatic way to implement Fibonacci would be to return an infinite lazy sequence from which you can simply take however many elements you want. There are lots of ways to implement this, one of which is to simply wrap a recursive implementation with lazy-seq:

user=> (defn fib [a b]
  #_=>   (lazy-seq
  #_=>     (cons a (fib b (+ a b)))))
#'user/fib
user=> (take 10 (fib 1 1))
(1 1 2 3 5 8 13 21 34 55)
user=> (take 20 (fib 1 1))
(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765)

Or, closer to your fib-until function:

user=> (take-while #(< % 100) (fib 1 1))
(1 1 2 3 5 8 13 21 34 55 89)

There are lots of other ways to implement Fibonacci lazily in Clojure.

I'll leave a lazy version of zeckendorf as an exercise ;-)

Regarding your question 2, using multiple arities the way you do is common and nothing to be concerned about IMHO.


I am a fan of loose coupling so I would suggest that you take the values of host, username, password and database out of your class. Pass the values through the constructor and set them in the constructor. This makes it easier to reuse your code.

Second, in classes such as one that creates a connection to a database I would not "echo" stuff. You better throw exceptions on error or return meaningful values to the caller.

Last, I'd suggest other names. This might be nitpicking but this has more meaning to me:

$connection = new DatabaseConnection();
$connection->open();
$connection->connectDatabase();

So, wrapped up I would have something like:

<?php
class DatabaseConnection
{
    var $host;
    var $username;
    var $password;
    var $database;
    var $myconn;

    function __construct($dbhost, $user, $pass, $db)
    {
        $this->host = $dbhost;
        $this->username = $user;
        $this->password = $pass;
        $this->database = $db;
    }

    function open()
    {
        $conn = mysql_connect($his->host,$this->username,$this->password);
        if (!$conn)
            throw new Exception('Error establishing a connection.');
        else
            $this->myconn = $conn;

        return $this->myconn;
    }

    function connectDatabase()
    {
        mysql_select_db($this->database);
        if(mysql_error())
            throw new Exception("Cannot find the database " . $this->database);
    }

    function selectData($query)
    {
        mysql_select_db($this->database);
        $result = mysql_query($query);
        return $result;
    }

    function closeConnection()
    {
        mysql_close($this->myconn);
    }
}
?>

Usage:

$connection = new DatabaseConnection("localhost", "root", "", "wilbert");
$connection->open();
$connection->connectDatabase();
$connection->selectData("SELECT a.student_id, a.FirstName, b.First_Name FROM Student a LEFT JOIN teacher b ON a.student_id = b.student_id");

See how the other names make more sense? Try to avoid verbs as a classname. Methods can and most likely will be or contain verbs, but not classnames. Also, leaving the query out of the class leaves you the option to use the same code for other queries.

Note that this is no perfect code, I was only suggesting what might be changed. Hope this helps! :)

Edit:

You call the function selectData() and pass the query-string as a parameter. This changes nothing, it gives the same result as your code. Only in my case you can pass other queries to the function whereas your function is limited to the embedded query.

Now for the result. This has also to do with the decoupling of your connection-class and what will be shown to the user. I showed u the usage of the class, the code below is how you can process the result. Create a function (but not in the connection class!) that returns the result in a table:

function resultTable($sqlResult)
{
    $table = "
";
    $table .= "
Student_ID	First_Name	First_Name
";

    while($row = mysql_fetch_array($sqlResult))
    {
        $table .= "
" . $row['student_id']. "	";
        $table .= "" . $row['FirstName'] . "	";
        $table .= "" . $row['First_Name'] . "
";
    }
    $table .= "
";

    return $table;
}

And the usage:

$connection = new DatabaseConnection("localhost", "root", "", "wilbert");
$connection->open();
$connection->connectDatabase();
$result = $connection->selectData("SELECT a.student_id, a.FirstName, b.First_Name FROM Student a LEFT JOIN teacher b ON a.student_id = b.student_id");
echo resultTable($result);

You could create a new class in which you define all sorts of methods like these to process a result and return it to the view-file where you will show it on the screen. Hope this clarifies it. :)


You seem to be very much over-complicating this. Here is an efficient solution:

Assuming a and b are positive numbers and the result is a valid 32-bit integer value

public int Multiply(int a, int b)
{
    if (a < 0 || b < 0)
        throw new ArgumentException("Numbers must be positive");

    var min = Math.Min(a, b);
    var max = Math.Max(a, b);

    if (min == 0 || max == 0)
        return 0;
    else if (min == 1)
        return max;

    int s = min >> 1;
    int halfProduct = Multiply(s, max);

    if (min % 2 == 0)
        return halfProduct + halfProduct;
    return halfProduct + halfProduct + max;
}

So what is happening here? First we need to sort these by the smaller and larger numbers, this reduces the number of iterations required. If either of the numbers is zero, then we return zero (since x*0 == 0). If the minimum number is 1, then we return max (since x*1 == x).

Now we can apply the shift operator since shifting one to the right divides the number by 2. By recursion we keep doing this until Multiply returns 0 or max. We can then determine the value if min is even by adding the two half-products or if min is odd by adding the two half products and max.

Again, even in your original solution this will break for negative numbers. You can code around that by switching the sign (Math.Abs) and swapping the sign at the end (0 - return value, unless both are negative then you leave it positive). I'll leave that as an exercise for you.


You are doing animation wrong. As a rule of thumb you shouldn't have your own infinite loop in a Tkinter program. Tkinter already has an efficient infinite loop — the mainloop function.

Here are a few Stack Overflow questions dealing with Tkinter animation:

simple animation using tkinter
Moving balls in Tkinter Canvas
Python Tkinter wireworld animation slowing down over time

I will say that the canvas has performance issues when there are hundreds of thousands of objects on the canvas, and it may start appearing when there are tens of thousands.

In your case, by my estimation you're creating a couple thousand canvas objects per second, and that's just way too many to expect good performance. Considering you're making a side-scroller, you simply don't need to create all those objects every second.


Simply reading the code already has a few things which stand out to me
(in general this all goes towards the style described in
this document, which is
standard to follow for Python code):

Compress_7z should start lower-case and probably should also say
compress_7zip.  I'm agreeing that the literal "7" would be
appropriate here, given the format name.
DAC is a bad variable name, as you've to read the docstring to even
begin to understand what this parameter is doing.  A better name might
be, well, delete_files_after perhaps.
The rest of the parameters should also all be lower-case.
Try and apply consistent formatting, or use an IDE or
command-line tool to do it
for you (right now there's no whitespace after some of the commas for
example, also some of the quotes are single and some are double for no
good reason).
The docstring is not very standard, though at least it mentions the
value range of the parameters, which is obviously good.

Next up, actual functionality:

Shelling out to the 7z utility is of course an option, although there
are also pure Python libraries for this as far as I can see.  The reason
I point this out is that for one the command-line utility might not be
installed and e.g. pip or a similar tool for Python might make it
easier to handle the dependency.

Since you've already settled on it though, a few more points about the
current implementation:

chdir in a library function is almost certainly a bad idea.  It's
completely not expected that "compress these files" also means "change
my current working directory".  Instead make sure that the function
works without by specifying file names reliably (that is, using
absolute path names, or by specifying the working directory for the
invoked process only).
Using strings as error values is a big no.  Use exceptions, or if you
absolutely do not want to do that, a properly structured return
value.  Right now you couldn't distinguish the return value of the
tool from the strings "Path does not exist" and that's generally to
be avoided.
If the compression level is a string the list.txt file will not be
cleaned up.  That's why you generally want to handle exceptions
properly, look up how
try, catch and finally work
for that.
Finally it seems like the subprocess.Popen invocation is too much
work.  If you don't have to communicate with the invoked process,
simply run it and wait for the result. time.sleep is an extremely
wasteful way of accomplishing the same.  Instead I think you might
just be able to use subprocess.run with the cwd argument (see
above) and be done with it.  You don't need shell=True either, since
the invocation doesn't use any shell features at all.


Ruby BST code for insertion implementation

I'll be writing this review assuming that BST stands for Binary Search Tree, and that you're only concerned with constructing the tree, not searching through it. With that in mind, let's start:

Node class

First, for the easy part: in your definition of Node#initialize, you've got a space between the method name and the parenthesis initialize (. While ruby read that fine (it'll even work if you take out the parenthesis all together), it's considered best practice to put the parenthesis right up against the method name, so def initialize(value).

Different methods of dealing with the children

Also, you do not need to initialize @left_child and @right_child to nil. Instance variables do not need to be initialized. If you try and manipulate an uninitialized instance variable, it will behave as if it is set to nil. So, you can simply exclude @left_child and @right_child from your Node#initialize method.

However, if you wanted to allow them to be passed in optionally, you can use arguments or parameters with default values. Here's an example of parameters with default values:

def initialize(value, left_child = nil, right_child = nil)
  @value = value
  @left_child = left_child
  @right_child = right_child
end

and here's and example with hash arguments with defaults:

def initialize(value, left_child: nil, right_child: nil)
  @value = value
  @left_child = left_child
  @right_child = right_child
end

I personally prefer the second, because in that case you could easily pass a right_child without the left_child and vise versa. Otherwise, to pass a right_child, you'd need to pass nil for left_child.

Also, you may want to validate that @left_child and @right_child are both Nodes. In that case, you would want to define attr_readers for those variables and not attr_accessors. You would manually define the accessors like so:

def left_child=(left_child)
  if left_child.is_a? Node
    @left_child = left_child
  else
    # Some handling for invalid left children, e.g.
    throw "Invalid left child: #{left_child}"
  end
end

and the same for @right_child. You could even do it for value too! Or, if you wanted to get fancier, you could define a private validate_node method to avoid duplication in left_node= and right_node=:

def left_child=(left_child)
  @left_child = validate_node(left_child)
end

def right_child=(right_child)
  @right_child = validate_node(right_child)
end

private

def validate_node(node)
  if node.is_a? Node
    node
  else
    throw "You've passed an invalid node: #{node}"
  end
end

In case you didn't know, private methods are methods that (without some ruby magic) cannot be called outside of that class. They are private to that class.

  Note: (Partially note to self) This probably isn't the fully best way to do this, the validation method should validate behavior rather than class. I should write more about that.

I think that's all for the Node class, so let's move onward!

BST Class

First off, I think that BST isn't that great of a name for this class. I'd go with Tree, because that is what it stores.

Anyways, first thing first: I'd make it possible to pass root to the initializer by making it an argument with a default value:

def initialize(root = nil)
  @root = root
end

Next thing's next: The #insert method!

I notice that you're checking if self.root is nil. In ruby, there's a slightly faster (IIRC) and much more ruby way of doing this: self.root.nil?. It's a neat, built-in nil check. In addition, there's no reason to modify @root using its accessor, you can actually just modify it directly.

Also, I noticed that wherever you return a value, you're either returning the root, or the node that was passed in. I also note that you're always setting the node that was passed in as the root. So, you're actually always comparing to root. With that in mind, here are some little bits of cleanup (incomplete, I'll come back and finish it):

def insert(value, node)
  # When this occurs, it will set @root.value == node.value
  @root = Node.new(value) if @root.nil?

  return @root if @root.value == value

  if node.value > value
    if node.left_child.nil?
      node.left_child = Node.new(value)
    else
      insert(value, node.left_child)
    end
  else
    if node.right_child.nil?
      node.right_child = Node.new(value)
    else
      insert(value, node.right_child)
    end
  end
  return node
end

Other notes

Here's an interesting example of how someone else implemented BSTs in ruby


From a once over:

As a caller I would rather whether start or end was not a string instead of getting ERROR: start and end must both be Strings!
Indentation! Please consider using something like jsbeautifier
You can merge these

var range = [];
range.push(current); //Put the start directly into the range.

into

var range = [start]; //Begin with the start <- Perhaps too zen a comment

Do not keep commented out code
I cannot understand why you would need

while(!stringEqual(current.split(""), end.split(""))) {

why can't you simply

while(current != end) {

Also, this, I cant see when you would need this:

if ( typeof item === "number" ) {
    return item++;

Since you verify that both start and end are string, this should never happen?
allAreZ is written in a convoluted way, in this type of function ( small, and dedicated to 1 task), it is appropriate to return immediately. You could try something like

function allZ( string ) {
    var i = 0;
    while ( i < string.length ) {
        if ( string[i] !== "z" ) {
            return false;
        }
        i++;
    }
    return true;
}

or, you something fun like this

function allZ( string ) {
    return string.split('z').length == string.length + 1;
}

I am mulling about writing something far shorter with .toString(26) To be sure zzzzzz equals 308915775, that is a lot of entries to store in array, in fact at this point it is silly to store this into an array. You would be better of writing an iterator class which provides a next() function for ranges in that size.

function charRange(start, end)
{
  if(typeof start !=  "string" ){
    throw 'start must be a string';
  }

  if(typeof end !=  "string" ){
    throw 'end must be a string';
  }

  var range = [],
      current,
      mapRadix = {},
      mapAlphabet = {},
      a = 'a'.charCodeAt(0);

  for( var i = 0 ; i < 26 ; i++ ){
    mapRadix[i.toString(26)] = String.fromCharCode(a+i);
    mapAlphabet[String.fromCharCode(a+i)] = i.toString(26);
  }

  function string2Number( s ){
    var i26 = '';
    for( var i = 0 ; i < s.length ; i++){
      i26 += mapAlphabet[ s[i] ];
    }
    return parseInt(i26,26);
  }

  function number2String( int ){
    var n = int.toString(26),
        s = '';
    for( var i = 0 ; i < n.length ; i++){
      s += mapRadix[ n[i] ];
    }
    return s;
  }

  current = string2Number( start );
  end = string2Number( end ) + 1;
  if( current > end ){
    throw 'start must be smaller than end';
  }

  while(current != end ) {
    range.push(number2String(current++));
  }

  return range;
}


Undo Framework Design (Revert the changes in the collection)

Edge cases

This fails to handle several edge-cases:

Undoing a remove action multiple times results in that item being added back multiple times.
Undoing an update action after other items have been inserted at a lower index causes the wrong items to be replaced.
Lists can contain duplicate items, but only the last operation for each distinct item is remembered.
Updating an item leaves the add-operation for the original item, but attempting to undo that add-operation fails unless the update action has first been undone.

As the last point demonstrates, you can't just undo an action without undoing all actions that followed it first. If you do want to support something like that, you'll have to clearly define the requirements and figure out what the desired behavior is for a variety of edge-cases. You'll also want to make this information available to those that will use this code (documentation, see below).

Implementation notes

Hiding methods with new is rarely a good idea: (changeList as IList<string>).Add("untracked item"); probably does not do what you want it to do. In this case, don't inherit from List<T>: implement the necessary interfaces manually, and use an internal List<T> for the actual storage.
List<T> (and IList<T>) provides some other methods (Insert, [int index] and Clear) that are not being 'intercepted', resulting in untracked changes.
Undoing an action is complicated. Why should the caller need to know whether to use NewValue or OriginalValue? That makes it difficult to use correctly. Why does the caller need to pass in any arguments at all? Why use a wrapper class if you can just create a closure with all the necessary state?
Try to use clear, descriptive names. UndoableAction and Undo are much clearer than ActionWrapper and Action, and Replace is a more accurate description of what the Update method does.
Those RevertAdd/Remove/Update methods don't seem to be intended for public use, so don't make them public. They only clutter the interface of your class.
Those ActionWrapper properties should probably not be public either, but if they have to be, then at least make them read-only. You don't want other code to be able to mess with the internals of your change-tracking/undo system. The same goes for that ActionMap property: it should only be exposed as a get-only IReadOnlyDictionary.
Documentation is entirely absent. That makes it even more difficult to tell how this class is meant to be used (or even what its exact purpose is), and various details such as Remove only removing the first matching item are left to the caller to figure out. It also makes it difficult for others to distinguish between intended and incorrect behavior.

Alternative design

I'd go for a different design, one that doesn't expose internal details, doesn't allow for out-of-order undoing (which means less edge-cases), and that provides a simple interface that's easy to use correctly (note how it's not possible to undo the same action multiple times):

public class ChangeTrackingList<T> // implements IList<T> and/or other interfaces
{
    private List<T> _items = new List<T>();
    private Stack<Action> _undoActions = new Stack<Action>();

    public bool UndoLastAction()
    {
        if (!_undoActions.Any())
            return false;

        var undoLastAction = _undoActions.Pop();
        undoLastAction();
        return true;
    }

    public void Add(T item)
    {
        _items.Add(item);

        // Ensure that this item gets removed, and not an identical earlier occurrence:
        var index = _items.Count - 1;
        _undoActions.Push(() => _items.RemoveAt(index));
    }

    ...
}


Determining the difference between odd and even numbers

Combining some of the existing answers, you can do

s.chars()                          // get the char stream
  .map(Character::getNumericValue) // convert to ints
  .map(n -> n%2==0 ? -n : n)       // negate the even ones
  .sum()                           // sum it all up

This will give you the sum of the odds and the negative evens, which is the same as the sum of the odds minus the sum of the evens.

edit

In response to @kai, for absolute max readability, I'd probably do (pseudocode)

List<int> ints = s.chars().map(Character::getNumericValue)
Map<Boolean, List<int>> intsEven = ints.partitioningBy(n -> n%2==0)
return intsEven.get(false).sum() - intsEven.get(true).sum()

or with isEven from the other answers and not defined here

List<int> ints = s.chars().map(Character::getNumericValue)
List<int> evens = ints.filter(isEven)
List<int> odds = ints.filter(not(isEven))
return odds.sum() - evens.sum()


Swap even and odd bits of unsigned 8-bit integer

OMDG arrays to manipulate bits
Bit manipulation is the most basic type of operation a computer can do. These days it can mess with 64 bit in one go. JS number (as signed int 32) is limited to 32 (to keep us in our place)
BTW JS has 8, 16, 32bit signed and unsigned arrays.
In JS you can write binary numbers with the 0b prefix. Eg 0b111 is 7
To swap even odd, you shift all bits to the left << 1 (same as * 2) and mask out & 0b10101010 the odd bits. The for the even you shift all bits to the right >> 1 similar to /2, mask out the even bits & 0b101010101 and add or or the result of the previous shift.
Example show two ways of doing the same thing.

const swapEvenOdd = char => ((char << 1) & 0b10101010) | ((char >> 1) & 0b1010101);

const swapEvenOdd2 = char => ((char * 2) & 170) + ((char / 2) & 85);

console.log(swapEvenOdd(0b01100110).toString(2).padStart(8,"0"))
console.log(swapEvenOdd2(0b01100110).toString(2).padStart(8,"0"))


Finding the longest common substring between two tweets

The classic solution to this well-known problem is using a Suffix array (see also Suffix tree and Generalized Suffix tree which is a more general data structure for these kinds of problems.). Basically, a Suffix array is a sorted set in which every suffix of every tweet is inserted. By using the prefixes of those sorted suffixes, you can find the longest common substring by iterating through every pair of substrings from different tweets in the Suffix array.

Construction of all suffixes can be performed in O(140 k) time, where k is the the amount of tweets, and 140 is the length of a tweet. These can then be sorted in O(k * log(k)) time. Finally allowing you to find the longest common substring in O(k 140) time. Which results in roughly 57 800 operations.

The algorithm proposed in your orignal post loops through every tweet twice, and has to, worst case, compare all the characters. This leaves a total complexity of O(k^2 * 140) which is 5 600 000 operations.

Example

Imagine you have three strings:

ababa
bataba
dafjkl

We generate all suffixes of every string. Every suffix of the first string is:

ababa
baba
aba
ba
a

For the second we have:

batabak
atabak
tabak
abak
bak
ak
a

And finally for the third:

dafjkl
afjkl
fjkl
jkl
kl
l

If we sort all suffixes for all strings, we get the following sorted set:

a
a
aba
ababa
abak
afjkl
ak
atabak
ba
baba
bak
batabak
dafjkl
fjkl
jkl
kl
l
tabak

Thus we iterate through every pair of suffixes for different strings, to find the longest common prefix in suffixes from two different strings. This is equal to the longest common substring.

First encounter is a (origining from the 1st string) and a (2nd string), thus our longest common substring (LCS) is of length 1 and equal to a.

We go to the next pair from different strings, which is aba/ababa and abak, both of length 3. This is set as the LCS so far. If you keep going through the set using this algorithm, you will find that this is the LCS for these three strings.

I do not know Java, however, I just created a C++ solution to a very similar problem. The solution for your problem is essentially the same, you just have to generate substrings for k strings rather than two.


I put the zr.open in the try because if the file does not exist it will throw exception, and if zip reader is left open it usually crashes the add-on.

Crash? I wouldn't know about that. But yes, it should be closed. But then again, only .close() it after it has actually been opened.

try {
  zr.open();
  try {
    // do some stuff
  }
  // another catch possible as well.
  finally {
    zr.close();
  }
}
catch (ex) {
  // handle
}

var reusableStreamInstance = Cc['@mozilla.org/scriptableinputstream;1'].createInstance(Ci.nsIScriptableInputStream);

  I'm resuing the input stream create instnace, how is it not safe?

The stream wrappers, or XPCOM in general really, usually have a contract that you should call .init() only once, unless stated otherwise. nsIScriptableInputStream does not state otherwise, and while it just works(tm) to call .init() again and again right now, that might change in the future.

Better create a stream wrapper per wrapped stream.

  Should I close the input stream instance after i am all done or everytime after init

Yes.

  Is Cu.forceGC needed? I'm not sure I thought it might be.

If you're not sure, then it is not needed. If you know it is "needed", check if there is another way. Manually calling the garbage collector does not only impact performance, it is - or at least used to be - a sure way to crash when calling it too often/too randomly.

  My exception checking is weird, I check the .name I'm not sure if this is the recommended way

Actually, you can check ex.result for nsIExceptions, even within the catch.

catch (ex if ex.result == Components.results.NS_ERROR_FILE_NOT_FOUND) {
  Services.ww.activeWindow.alert('XPI at path does not exist!\n\nPath = ' + pathToXpiToRead);
}
catch (ex) {
  console.warn('exception occured = ', ex);
}

My take

var {classes: Cc, interfaces: Ci, results: Cr, Constructor: CC, utils: Cu } =
  Components;

let ZipFileReader =
  CC("@mozilla.org/libjar/zip-reader;1", "nsIZipReader", "open");
let ScriptableInputStream =
  CC("@mozilla.org/scriptableinputstream;1", "nsIScriptableInputStream", "init");

function handleEntry(name) {
  try {
    let entry = this.getEntry(name);
    if (entry.isDirectory) {
      console.log(name + " is directory, no stream to read");
      return false;
    }
    let stream = new ScriptableInputStream(this.getInputStream(name));
    try {
      // Use readBytes to get binary data, read to read a (null-terminated) string
      let contents = stream.readBytes(entry.realSize);
      console.log("Contents of " + name, contents);
    }
    finally {
      stream.close();
    }
    return true;
  }
  catch (ex) {
    console.warn("Failed to read " + name);
  }
  return false;
}

try {
  var xpi = Services.dirsvc.get("ProfD", Ci.nsIFile);
  "extensions/noverflow@sdrocking.com.xpi".
    split("/").forEach(p => xpi.append(p));

  let reader = new ZipFileReader(xpi);
  try {
    let entries = reader.findEntries('*');
    while (entries.hasMore()) {
      let name = entries.getNext();
      if (handleEntry.call(reader, name)) {
        console.debug("Handled entry " + name);
      }
    }
  }
  finally {
    reader.close();
  }
}
catch (ex if ex.result == Cr.NS_ERROR_FILE_NOT_FOUND) {
  Services.ww.activeWindow.alert("XPI at path does not exist!\n\nPath = " + xpi.path);
}
catch (ex) {
  console.warn("exceptional exception", ex);
}

Edit I moved xpi into the try-catch block, so it doesn't pseudo-leak (becomes a global variable, i.e. this.xpi or window.xpi).

Nested try-blocks

As you asked for this in the comments...
First lets see what happens with this:

try {
  try {
    throw new Error("oops");
  }
  finally {
    console.log("finally");
  }
}
catch (ex) {
  console.error("outer", ex.message);
}

Result

"finally"
"outer" "oops"

Now, if we already caught the exception in the inner try-block by adding a catch block

try {
  try {
    throw new Error("oops");
  }
  catch (ex) {
    console.error("inner", ex.message);
  }
  finally {
    console.log("finally");
  }
}
catch (ex) {
  console.error("outer", ex.message);
}

Result

"inner" "oops"
"finally"

And now, lets re-throw the error.

try {
  try {
    throw new Error("oops");
  }
  catch (ex) {
    console.error("inner", ex.message);
    throw ex;
  }
  finally {
    console.log("finally");
  }
}
catch (ex) {
  console.error("outer", ex.message);
}

Result

"inner" "oops"
"finally"
"outer" "oops"

So there you have it. Any given exception will be caught only once, by the nearest enclosing catch-block, unless it is re-thrown. Of course any new exceptions raised in "inner" block (because code in catch-block way do something that throws ;) will be caught by the "outer" block.


First, I'll show you some essential feature your class is missing, then I'll show you a way to use modern features of C++ to automate parts of your code.

Fixing your current code

Use const to have the compiler check your logic

If a method does not modify the class, then it should be declared const so that other functions can call it when acting on an instance that is not allowed to be changed. For example,

bool isEmpty() const
{
    return top == nullptr;
}

Now, a function that takes a const Stack& parameter can check if the Stack instance is empty. Similarly, the getTop() and display() methods should be marked const since neither modify the stack.

Clean up your resources

First, some sample code:

int main()
{
    int sizeOfStack;
    std::cin >> sizeOfStack; // ask user for a number
    if(sizeOfStack < 10)
    {
        Stack stack;
        for(int i = 0; i < sizeOfStack; ++i)
        {
            stack.push(i);
        }
        stack.display();
    }  // All data added to stack is leaked here
    else
    {
        std::cout << "Too large for this example.\n";
    }

    // The memory taken up by the stack cannot be released
    // until the program exits.
}

As your code is now, when your program exits a scope (a part of code that is enclosed in curly braces like a function, loop, or if-else-block), all of the data you created with new will be leaked. This means that the data will still exist and take up memory and other resources, but there will be no way to access it to clean it up.

In C++, every class that has a data member that does not have its own destructor (usually pointers) needs a destructor to manually clean it up. This is a method named like a constructor but prefixed with a tilde: ~Stack(). For your Stack class, you would need something like

~Stack()
{
    while( ! isEmpty())
    {
        pop();
    }
}

Write constructors to ensure data is always valid

In C++, a class and a struct are nearly identical concepts. The only difference is that the data in a class is private by default and data in a struct is public by default. Otherwise, anything you can write in a class you can write in a struct. So, you can write a constructor for your Node class.

Node(int inputData, Node* inputNext)
{
    data = inputData;
    next = inputNext;
}

A better way to write this is to use an initializer list:

Node(int inputData, Node* inputNext) : data(inputData), next(inputNext)
{
}

Similarly, for the Stack class:

Stack() : top(nullptr)
{
}

It's not so important with ints and pointers, but with more complex classes you'll write in the future, using intializer lists will avoid some unnecessary work.

Now that Nodes have a constructor, you can simplify your push() method.

push(int value)
{
    top = new Node(value, top);
}

The constructor of the Node class centralizes the logic of creating a new Node so you don't have to rewrite it everywhere.

Use methods and other named code to make your intent clear

Many places in your code check if top == nullptr. You should use the isEmpty() to tell readers of your code (including you in the future) what you actually care about.

void pop()
{
    if ( ! isEmpty())
    {
        Node *n = top;
        top = top->next;
        delete n;
    }
}

This goes for getTop() as well.

Decide how to handle copying and assignment

As it is now, when an instance of Stack is copied, both instances will refer to the same data and modifications to one instance may affect the other.

Stack s1;
s1.push(7);
Stack s2 = s1;
s2.push(21);
s1.display();
std::cout << "\n\n\n";
s2.display();

This will result in the following output before crashing:

                        TOP ELEMENT
---------------------------------------------------------
Data: 7         Address: 007AF1C0       Next: 00000000
---------------------------------------------------------

                        TOP ELEMENT
---------------------------------------------------------
Data: 21                Address: 007AF230       Next: 007AF1C0
---------------------------------------------------------
                             |
                            \|/
---------------------------------------------------------
Data: 7         Address: 007AF1C0       Next: 00000000
---------------------------------------------------------

Notice that both nodes with the value 7 have the same pointer address. Now that the Stack class has a destructor, copying and assignment need to be handled to avoid deleting the same pointer address more than once. The simplest way is to disallow both.

Stack(const Stack& other) = delete; // delete the copy constructor
Stack& operator=(const Stack& other) = delete; // delete the assignment operator

With these lines in your class declaration, the following code will not compile:

Stack s1;
Stack s2 = s1; // error: Stack cannot be copied
Stack s3(s1); // error Stack cannot be copied

Stack s4;
s4 = s1; // error: Stack cannot be assigned to.

If you want your Stack class to be copyable, then you need to explicitly copy all of the data from one to the other.

Stack(const Stack& other) : top(nullptr)
{
    if( ! other.isEmpty())
    {
        top = new Node(other.top->data, nullptr);
    }
    else
    {
        return;
    }

    Node* bottom = top;
    for(Node* n = other.top->next; n != nullptr; n = n->next)
    {
        bottom->next = new Node(n->data, nullptr);
        bottom = bottom->next;
    }
}

After adding the copy constructor, you can rerun the code with s1 and s2 and see that the nodes containing the value 7 are at different addresses.

I'll leave writing the assignment operator as an exercise for you.

Tell the user when a request cannot be completed

Right now, when a user calls getTop() on an empty Stack, the user still gets an answer. Unless the user of this class sees the comment that INT32_MIN is never a valid value, there's no indication that anything went wrong. You may not have need of data values outside of [-100, 100], but what about future users (including your future self)? Why should your class not be allowed to store INT32_MIN as a valid piece of data?

It is better to tell the user that there is no data to be had. One way, if you are using C++17 (which may require a compiler flag or changing an IDE option), is to return a std::optional<int> (reference).

#include <optional>

// ...

std::optional<int> getTop()
{
    if(isEmpty())
    {
        return std::nullopt;
    }
    else
    {
        return top->data;
    }
}

The other option is to throw an exception in the empty case.

This way the caller of getTop() has to check if there is any data to be had.

Other notes

In the display() method, you can use a for-loop instead of a while loop to centralize all of the looping logic.

void display()
{
    for(Node* n = top; n != nullptr; n = n->next)
    {
        // output
    }
}

One more nitpick, you don't need the keyword struct in the Node::next declaration.

struct Node {
    Node(int inputData, Node* inputNext) : data(inputData), next(inputNext) {}
    int data;
    Node* next;
};

Using modern C++ features

A great way of improving this code is to use smart pointers. The std::unique_ptr (reference) tells readers, users, and the compiler that the variable or class containing the unique_ptr is responsible for cleaning up the variable when it is no longer needed.

So, you can change your Node class to

#include <memory>

struct Node {
    Node(int inputData, Node* inputNext) : data(inputData), next(inputNext) {}
    int data;
    std::unique_ptr<Node> next;
};

And the Stack class turns into

class Stack {
private:
    std::unique_ptr<Node> top;
// ...

Now, when a stack instance leaves the scope where it was created, the top node is automatically deleted. When top is deleted, top->next is automatically deleted, and then top->next->next, and then top->next->next->next, etc. So, you no longer need an explicit destructor (~Stack). The compiler will generate the correct destructor for you.

Now, you no longer have to call delete on any pointers. For example, the pop() method is now reduced to

void pop()
{
    if( ! isEmpty())
    {
        top = std::move(top->next);
    }
}

The std::move() call means that the contents of top->next--both the data and the pointer to the top->next->next node--will be stolen and moved into top. The previous contents of top will be deleted as this happens.

The other places where pointer manipulation changes is anywhere new is called. The push() method is now written with smart pointers as

void push(int value)
{
    top = std::make_unique<Node>(value, top.release());
};

The release() method returns the raw (non-smart) pointer held by the smart pointer and removes all responsibility for deleting it from that smart pointer. This happens so that the new smart pointer being added takes over responsibility for deleting the data when it is no longer needed. Assigning the new std::unique_ptr to top means that the Stack instance is now responsible for deleting the newly created Node.

Finally, if you don't want your Stack class to be copyable or assignable, you no longer need to delete those functions, since they will no longer be automatically generated. Instances of std::unique_ptr are not copyable or assignable, so any class they are a part of will lose those qualities as well. If you want to make your class copyable, you'll need the get() method of the std::unique_ptr. This returns the raw pointer like the release() method, but the std::unique_ptr retains responsibility for deleting the Node. This will allow your program to follow the linked list chain without copying std::unique_ptrs.


Sending data to a database in size-limited chunks

I waited a few days to get other answers to your questions. now I feel I can add my 2 cents.

First off, the obvious: This is one single method. It does:

Polling a queue
Serialising a message into a byte[]
Validating the messages
Packaging in 50Kb packages
Sending chunks to a Database

The obvious thing to do is split those actions into individual methods, and move the right methods into the right objects which allow you to use a nicer syntax (right now, too much is in the current single method of the current objec, so your hands are tied).
Our goal is to make your code more readable, like this:
public void batchSend(final Partition partition) {
    Queue<DataHolder> dataHolderQueue = dataHoldersByPartition.get(partition);
    DataHolder data = dataHolderQueue.poll();
    Message message = new Message();
    while (data != null) {
        if(data.isValid()){
            if(message.hasRoomFor(data)){
                message.append(dataHolder);
            } else {
                // Message is at maximum capacity, send it
                database.send(message);
                message = new Message();
            }
        }
        data = dataHolderQueue.poll();
    }
    if(!message.isEmpty()) {
        database.send(message); // Queue is empty, sending remaining message
    }
}

I simply modified the Message Object, which now holds a bunch of DataHolder's serialized data and tells you when you reach a certain size limit. I don't really understand how you concatenate the messages together (it's all hidden in the Message class, which was not included) so most of the below is just a guess:
public class Message {
    public static final int MAX_BYTES_PER_MESSAGE = 50000;
    private final Map<byte[], byte[]> data = new HashMap<>();
    private int size = 0;
    ... Other fields I don't know about ...
    public boolean hasRoomFor(DataHolder holder){
        return size + holder.getSizeIncludingHeader() <= 50000;
    }
    public void append(DataHolder holder){
        byte[] clientKeyBytes = dataHolder.getClientKey().getBytes(StandardCharsets.UTF_8);
        byte[] processBytes = dataHolder.getProcessBytes();
        size += clientKeyBytes.length + processBytes.length;
        // Maybe throw InvalidOperationException is size > 50000 ?
        data.put(clientKeyBytes, processBytes);
    }
    public boolean isEmpty(){
        return map.isEmpty();
    }
    // provide getters on the data field for sendTodatabase() method
    ... Other methods I don't know about ...
}

Also modified the DataHolder Object to add:
public boolean dataHolder.isValid(){
    return dataHolder.getClientKey().getBytes(StandardCharsets.UTF_8) <= 255;
}

Indeed, its validity seem to be an intrinsic property of a DataHolder. By this I mean a DataHolder either is valid, or isn't, but it does not depend on external factors. This is a perfect candidate to be made a method of the DataHolder Object.

Weird message usage
This is weird:

   Message message = new Message(partition, clientKeyBytesAndProcessBytesHolder);
   sendToDatabase(message.getAddress(), message.getLocation());

You're creating an instance of message, but not using the instance, only some of its fields, via getters. The point of using a Message Object is to keep its constitutive elements consistent inside, so those elements are only consistent if using the instance.
By allowing sendToDatabase to have two split parameter, you're allowing the caller to pass two inconsistent parameters:
sendToDatabase(anAddress, aTotallyUnrelatedLocation);

The obvious fix is to pass in the Message Object entirely, the method will just extract the right data:
boolean sendToDatabase(Message message){
    Address address = message.getAddress();
    Location location = message.getLocation();
    ... do Stuff
    return successStatus;
}

It is additionally syntaxically more pleasing to send a Message rather than an address and a location.
By the way, why would the message body not be sent as well? This is confusing. I would have expected sendToDatabase(Message message, Address address) at least. Maybe the Location is the Message body? It does not make sense to me.

GC Handling
This should never be written:

clientKeyBytesAndProcessBytesHolder.clear(); // watch out for gc

The GC knows his stuff. Don't 'help' him. It knows if the collection needs to be GC'ed, or if the data in it does. This call doesn't even make the memory available!
If the collection must be cleared, it must be for business reasons, not because of GC.
Also be careful, if you clear() it, but the sendToDatabase() spawned a Thread which holds onto the reference a bit longer, you've just deleted all data before it was sent.
The best would be to overwrite the reference to the collection with a new one:
clientKeyBytesAndProcessBytesHolder = new HashMap<>();

With this, you signal to the GC that it can get rid of the Collection (you no longer keep a handle), so when no one else holds a reference either, it will be recycled.

Late validation
I wonder why you validate() your messages so late. You only validate them just before sending them. You could do this check earlier, for example when the message is sent to the queues.
This is the "Fail Fast" principle: Don't keep corrupt data in your system, flush them as soon as you can.

Edit:
One shortcoming of this code is I might perform several dataholder-to-byte conversions. If those are not complex, it's fine. If they are, here is a Workaround:
Create a ValidatedRawData Object wich contains just the raw byte data.
It would be created by the DataHolder itself in a re-write of validate() method: so:
public class DataHolder {
    ... stuff ...
    /** Now returns null if fails to validate */
    public ValidatedRawData validate(){
        byte[] clientKeyBytes = dataHolder.getClientKey().getBytes(StandardCharsets.UTF_8);
        if (clientKeyBytes.length > 255)
            return null;
        byte[] processBytes = dataHolder.getProcessBytes();
        return new ValidatedRawData(clientKeyBytes, processBytes);
    }
}

ValidatedRawData is just a holder, with Getters.


Python: screen colors adjuster using Turtles

Review
I wasn't able to figure out a way to make the code more compact and in my opinion the code is pretty clear. However I do have some other feedback.
Use a proper main
Instead of:
turtle.setworldcoordinates(0, 0, 4, 255)
turtle.colormode(255)
turtle.tracer(False)
turtle.bgcolor(0,0,0)

...

def main():
    spawningPainters()
    assign_painters()
    listening_input()

main()
turtle.listen()
turtle.tracer(True)
turtle.mainloop()

Do:
...

if __name__ == "__main__":
    turtle.setworldcoordinates(0, 0, 4, 255)
    turtle.colormode(255)
    turtle.tracer(False)
    turtle.bgcolor(0,0,0)

    spawningPainters()
    assign_painters()
    listening_input()

    turtle.listen()
    turtle.tracer(True)
    turtle.mainloop()

For more information you can look at this post: https://stackoverflow.com/questions/419163/what-does-if-name-main-do
Prevent the turtle from going outside of the window
With the current code it is possible to drag the turtle outside of the window. If you then stop dragging you cannot get it back unless you reset the position. To prevent this from happening we can limit the boundaries of y inside of the draw functions.
def draw_blue(x, y):
    bluePainter.ondrag(None)
    x = blue_x
    y = min(y, 255)
    y = max(y, 0)
    bluePainter.goto(x, y)
    bluePainter.ondrag(draw_blue)
    update_screen_color()

By doing this the min and max calls can be removed from the update_screen_color function. However you may want to leave them as a form of defensive programming in case you add more features.
def update_screen_color():
    red = redPainter.ycor()
    green = greenPainter.ycor()
    blue = bluePainter.ycor()

    turtle.bgcolor(int(red), int(green), int(blue))

Update screen color when going back to the origin
When the position is put back to the origin the screen color is not redrawn. Unless this is intended it would be good to call the update_screen_color function at the end of the back_to_origin function.
Few tips
The global painter variable is not used anywhere outside of the spawningPainters function, so it can be removed.
Move the colors list to the spawningPainters function as it is not used anywhere else.
You might want to rename spawningPainters to spawn_painters.
Extra
Add typing to the painters list
When an empty list is declared the intellisense of your IDE may have trouble figuring out what type of elements the list will contain. By adding type annotations you can help the intellisense better understand your code.
Instead of:
painters = []

Do:
from typing import List

...

painters: List[turtle.Turtle] = []


Including functions in _ViewStart.cshtml

The ConvertControllerNameToCssClass function has limited use, in that it is not likely to be used elsewhere and shouldn't be used elsewhere either.

It looks like the function converts a PascalCase input text to dash-separated-words format.
This is actually a quite common text transformation to do.
In some frameworks it's called "slugify",
and I would prefer this shorter name instead of the current very long name.
(Another naming idea: ToCssClass)

You seem to have a bug:
you check if the input is null,
but you don't check if it's empty.
If it's empty, then this line will throw an exception:

    sb.Append(text[0]);

Instead of transforming the input character by character,
it would be much simpler to use a regex.
I don't know the syntax in C#,
I hope this Perl/Bash example might help:

$ perl -pe 's/[A-Z]/-\L$&/g; s/^-//' <<< HelloWorldThere
hello-world-there


Wrath Cookie Switch for Auto Golden Cookie Clicker

How could I do this a little better?

Initially my eyes are directed at the two branches of the conditional and ways to eliminate the redundancy. Would it be too long of a line to move that conditional check of wrathCookieSwitchOn inside the if inside the forEach?
Game.shimmers.forEach(function(shimmer) {
    if (shimmer.type == "golden" && (wrathCookieSwitchOn || shimmer.wrath == 0) {
        shimmer.pop()
    }
})

It must be asked whether the type of shimmer.wrath needs to be an integer. If any falsely value will suffice, then shimmer.wrath == 0 could be simplified to !shimmer.wrath, otherwise, use strict equality: shimmer.wrath === 0
Beyond that, the only idea I have possibly removing the closure by some technique like currying or just defining a function... or if ES-2015 is an option, simplify it into an arrow function.
Update
In response to your answer, I shall reveal another option I considered, which some argue might be less readable, but yes, like you typed: “if we are going to one-line it, let's one-line it!”:
Game.shimmers.forEach(function(shimmer) {
    shimmer.type == "golden" && (wrathCookieSwitchOn || shimmer.wrath == 0) && shimmer.pop();
});

Which would lend itself well to an arrow function (if permissible).


First I see that both classes depend on each other and are tightly coupled together.  Why does a Card object need to know its own index in an Array?

Secondly, the Card object updates the game object, but the game object contains an array of the cards, which means the Game object owns a bunch of Card objects.

If you were to remove the dual dependency, then you could rewrite your isMatch method to be

    isMatch: {
        value: function(inCard) {
            return (this.val == inCard.val);
        }
    }


Edit: about the new method, I'd say Graphics2D is a bit overkill (look at Konrad Rudolph's comment for another opinion). And you don't use the max parameter anymore. Does it stretch the image?

The original method is better, but you should have a real if else: resizing the image twice is a hack. It would look like this: you just have to fill in the if.

public static ImageIcon resizeImage(ImageIcon imageIcon, int width, int height, boolean max) {
  Image image = imageIcon.getImage();
  Image newimg;
  if(/* think what condition would work here */) {
    newimg = image.getScaledInstance(-1, height, java.awt.Image.SCALE_SMOOTH);
  } else {
    newimg = image.getScaledInstance(width, -1, java.awt.Image.SCALE_SMOOTH);
  }
  return new ImageIcon(newimg);
}

I think the helper methods are useless since there is no abstraction: it just does two separate things. This does not help that much, and it's better if opening the file is explicit: the code is easier to read.


Algorithm that spans orthogonal vectors: Python

You should probably be using Numpy, although I don't know enough about your situation to comment any further.

Assuming that you need to retain "pure Python", the following improvements can be made:

Negation

Replace (-1)* with -

Generators

Replace your for k in range(dimension-1): loop with

orthogonal_vec = [
    random.randrange(-1000,1000)
    for _ in range(dimension-1)
]

Type hints

n: int, vec: typing.Sequence[float] (probably) . And the first two functions return -> typing.List[float]. cross_product both accepts and returns float.

Inner list

sum([ ... ])

shouldn't use an inner list. Just pass the generator directly to sum.


Parsing a string of the form "key1=value1;key2=value2;" into a Hash

You can make it a single expression by taking advantage of Hash[[key, value], …] (available since Ruby 1.9).

The function name could probably be improved.

When using String#split, I consider it good practice to limit the number of splits whenever a limit may be applicable.  Here, you wouldn't be able to tolerate a second = sign within each key=value string, so you should use pair.split('=', 2).

def to_hash(str)
  Hash[
    str.split(';').map do |pair|
      k, v = pair.split('=', 2)
      [k, v.to_i]
    end
  ]
end


Dynamically initializing Context and creating connection string for Web API

I am not familiar with Dapper, but my assumption is that the objectives of using it are similar to using any other data access framework. Just from looking at their GitHub page, it looks like a very nice tool.

Unfortunately, maintaining compatibility with old applications is the reality that enterprises have to deal with, so in concept, I don't think this is a terrible idea. I would suggest doing something to ensure you have good connectivity between your API and your databases, though. If your company uses QOS, and the MSSQL traffic is not prioritized, but HTTP is, then using a SOAP service at the data source might be a good idea, and then just forward the request to that service. Web API would also be good, but implementation is a little more complex. That may be okay, though, if you want to avoid the overhead of SOAP envelopes.

From an API perspective, I would not recommend using custom HTTP headers. Part of the goal of Web API is having a standards compliant HTTP endpoint. Although that does not exclude using custom headers, I think that it might be better to try and device a custom route for the legacy integration, in places where you do not need to integrate with the modern systems. An alternative approach, if the intent is to store the data twice, is to dependency inject both your EF context, and your legacy adapter, into the controller. When the legacy adapter can go away, you "just" remove it from your controller. That way, you can integrate it across all of your API, and provide as seamless an experience as possible for your consumers.

Good luck with your implementation. I'm working on resolving several legacy applications myself, and it seems to be tough work whenever I hear anyone mention it.


Is my N-drome (variation of palindrome) checking program efficient?

I'm not a Java programmer, but I'll point out some familiar syntactical things I see:

You should separate the logic by putting the checking code into a separate function, leaving main() to call the function, handle the input/output, and terminate when needed.
What is the purpose of y?  From the looks of it, it's used to hold an "error condition" for indicating whether or not the inputted string is an N-drome.  If so, I think this should be a boolean type and given a relevant name.  Either way, y should be renamed to reflect its purpose.

What about strings a and b?  Are they the leftmost one and the rightmost one for the original string?  You should write out the purpose of these single-char variables to give them more meaning.
The lack of an increment value in the for-loop doesn't look too clear.  If someone wanted to see what the loop should do after each iteration, they would have to fish through the loop body.  If the loop won't be incremented in each control path, then it may not be the best loop type to use.
I'm not familiar with break here, but it looks like a goto in C++.  I don't think something like that should be done with a loop (or probably anything practical).  Again, you may need to rethink how you approach this loop type and execution.


I would want to understand how the infinite scroll is actually being applied.

Do you understand what javascript events actually trigger new items to be added?
Does it make more sense to simply trigger those events vs. worry about physically scrolling the browser?
Is the content being delivered via AJAX? Can you just query the AJAX endpoint more directly to get to the data you want to get?
Is there anything from the ajax response that you need to understand to know when you have reached the end of the list (no more items to be added)?

When you think through these you might find you have a better way to approach the problem.


Your result wrapper sounds like a good idea. I would modify it by allowing a collection of error strings, in case of multiple errors, warnings and the like, or perhaps consider holding an inner exception type (depending on how you raise these errors).

I am, on the other hand, wondering why you've hidden the constructor and opted for two static factory methods. As far as I can tell they offer nothing over simply offering two constructors instead, and they make for a less intuitive creation process for other developers (who will assume a constructor before trying other options):

public class Result
{
    public bool Success { get; private set; }
    public string Error { get; private set; }
    public MyClass MyClass { get; private set; }

    public Result(MyClass myClass)
    {
        Success = true;
        MyClass = myClass;
    }

    public Result(string error)
    {
        Error error;
    }
}

If you are concerned that other programmers could confuse the constructors, consider XML comments, or possibly keeping Result as a baseclass, and create SuccessResult and  FailedResult subclasses like so:

public abstract class Result
{
    public abstract bool Success {get;}
}

public class SuccessResult : Result
{
    public override bool Success { get {return true; }}
    public MyClass MyClass { get; private set; }

    public Result(MyClass myClass)
    {
        MyClass = myClass;
    }
}

public class FailedResult : Result
{
    public bool Success { get {return false};}

    public string Error { get; private set; }

    public Result(string error)
    {
        Error error;
    }
}

This successfully conforms to the Single Responsibility Principle, here a result only contains error information if an error actually occurs. From this point you could also extend Result (or FailedResult) to create an ExceptionResult as well, which would contain any Exceptions raised and providing more detailed information on the nature of the error.

As for your second part, I would leave it out. The implicit conversion gives me the impression I'm getting a boolean value of the result itself, not of its success/failure condition.