Generating readable text in a human language from machine-readable data

I see a couple of potential issues with regards to internationalization:

pluralization is more complex than (qty == 1 ? singular : plural). What about the value 0? Also in some languages, different plural forms are in use depending on the number.
numbers should be formatted according to language, using appropriate separators
concatenation (that you mention is done in main program) must be avoided because the order of words and phrases will often vary in translations in different languages

I would advise to :

localize translations using named parameters to be replaced: this solves the ordering issue, and avoids concatenation.
format values, for number formatting and pluralization, using a separate function localized for each language
replace parameters with formatted values in parameterized translations using a template engine: this should keep some potentially buggy regular expressions out of your code :)

You may be interested in having a look at:

JavaScript Internationalisation, a post by Matthew Somerville on 24 Ways
jQuery-global, "a jQuery plugin for the globalization of string, date, and number formatting and parsing"

and last but not least, the i18n API part of the Scalable JavaScript Application framework, which I designed for Legal-Box :)

eric-brechemier/lb_js_scalableApp, the project home page on GitHub
lb.core.Sandbox.js, check the i18n part of the API, methods starting with "i18n."

I may be able to provide more practical suggestions if you show more of your code, especially at the "top", part of the main program.


Welcome to ruby :), here are a few changes you might want to consider.

#!/usr/bin/ruby

class LuhnyBinChecker

  def initialize(number)
    @number = number
  end

Try to keep your methods pure without i/o, and collect the i/o in some portion that is dedicated to it. It helps later while you refactor the code. It is also nicer to not to rely on member variables too much, and preserve the referential transparency of functions where possible.

  def check
    arr = digits(@number)
    puts "Checker: doubling every second number from the right.."
    arr = doubleSecond(arr)
    puts "Checker: calculating the sum.."
    getResult(sumNumbers(arr))
  end

Always be on the lookout for things you can refactor and reuse.

  def digits(n)
    n.to_s().scan(/\d/).map{ |c| c.to_i }
  end

Two ways of doing the doubleSecond, I prefer the second way, and I think that is a more ruby way. But as a beginner, you might understand the first better. Choose which ever you like.

  def doubleSecond(arr)
    #arr.each_with_index do |item, i|
    #  arr[i] = arr[i] * 2 if (i %2 == 0)
    #end
    arr.zip((1..@number.length).to_a()).map do |e|
       e[1] * ((e[0] % 2) + 1)
    end
  end

  # treat numbers >= 10 individually
  # e.g. 12 -> 1 + 2 = 3
  def sumNumbers(arr)
    arr.map{|i|
        i > 9 ? splittedSum(i) : i
    }.inject(0,:+)
  end

You can think of Array.inject(0,:+) as Array.sum()

  def splittedSum(number)
    digits(number).inject(0,:+)
  end

  def getResult(sum)
    sum.modulo(10) == 0
  end
end

It is nicer to have a guarantee that a CreditCard will always contain a number rather than to check for nil in the getter method.

class CreditCard
  attr_reader :number
  def initialize(number)
    @number = number
  end

  def verify
    (LuhnyBinChecker.new(@number)).check
  end
end

You can use abort if some conditions fail to satisfy.

if __FILE__ == $0
  puts "Please enter the credit card number to check:"
  input = gets()              # input card number
  abort "Please enter only numbers." if input !~/(\d+\s)+/
  card = CreditCard.new(input)
  puts "You entered: " + card.number
  puts "Verifying card number now..."
  if card.verify()
     puts "Credit card number is valid"
  else
     puts "Credit card number is valid"
  end
end


I'm not sure if using classes is better or worse but I am starting to see files being called as functions more than a single file with function within. This is a more common upload script.

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 20000)
    && in_array($extension, $allowedExts)){
    if ($_FILES["file"]["error"] > 0){
        echo "Error: " . $_FILES["file"]["error"] . "
";
    }
    else{
        echo "Upload: " . $_FILES["file"]["name"] . "
";
        echo "Type: " . $_FILES["file"]["type"] . "
";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB
";
        echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
}
else{
    echo "Invalid file";
}


Localization

In my experience, translations are often provided per language, so I would normally store them per language rather than per piece of text.

I also prefer to have a single 'localization' object, rather than many 'translatable strings'. It gives me a clear entry-point for loading translations into memory and it provides a simple interface to other code: a single object with a GetText(string languageCode, string key) method.

Most applications only use a single language most of the time, so you may not even need to load all translations into memory. A central localization object makes it easier to perform such optimizations.

Some localization systems use the default (often English) text as a lookup key. But lately I've been using 'hierarchical' keys instead, such as MainWindow.Menu.FileButton or Settings.DataSources.DataSourceName. It gives translators slightly more context, which makes it easier for them to provide more accurate translations. And sometimes, where the default language uses the same word, another language uses different words depending on context. The hierarchical aspect of these keys allows me to organize the translations somewhat, so it's easier to prevent duplicate entries and all that.

Other notes

I don't think implicit conversion operators are a good idea here. They only really make sense when you're converting between similar types, and only when there's no risk of data loss. That's not the case here:

Converting a string to a TranslatableString gives you a translatable string that doesn't contain any translations. I don't see why that is useful, since the whole point of this class is to give access to translations.
Converting a TranslatableString to a string gives you the default text, but you lose all the translations. Instead, I would turn that Text field into a property with a public getter.

TranslatableString only needs one constructor if you give the value parameter a default value: (string value = null). Also, C# 6.0 introduced auto-property initializers, so you can further reduce code repetition in constructors: public List<Translation> Translations { get; set; } = new List<Translation>();
Making that Translations property publicly settable is probably not a good idea. I assume you're doing it for the free serialization, but it also allows any other code to modify it.
It's good to see some documentation! Perhaps you could add a small example with some hierarchical language codes for those that haven't memorized their ISO standards?

The ToTranslatedString method

It's doing double work. if (Any()) item = First() has to find a matching item twice. item = FirstOrDefault(); if (item != null) only has to find the item once.
A dictionary that maps language codes to translations would be a more appropriate data structure here.
Rather than repeatedly calling ToLower(), obtain a lower-case code beforehand, and make sure that your translations only use lower-case codes internally.
The main lookup code is duplicated. Instead of an if/else construction and a loop, you only need a loop. You just need to generalize the language code after you've tried to find a match.
You'll probably want to ignore a translation immediately if it's empty, rather than checking that at the end. Currently your code won't try to find a more general translation in such cases.
GetTranslation(string languageCode) is probably a better name - To implies some kind of conversion.

An improved version could look somewhat like this:

private Dictionary<string, Translation> _translations = new Dictionary<string, Translation>();

public string GetTranslation(string languageCode)
{
    languageCode = languageCode.ToLower();
    while (true)
    {
        if (_translations.TryGetValue(languageCode, out Translation translation) && !string.IsNullOrEmpty(translation.Text))
            return translation.Text;

        // Try again with a more general language code, if possible:
        var dashIndex = languageCode.LastIndexOf('-');
        if (dashIndex == -1)
            break;

        languageCode = languageCode.Substring(0, dashIndex);
    }
    return Text;
}


Underscore-case version of ActiveRecord model's name

You can use the singular method of ActiveModel::Naming:

ActiveModel::Naming.singular(my_active_record_instance)

Alternatively, you can use the model_name method that's mixed in to ActiveRecord by the same ActiveModel::Naming module. However, it's not available on a record instance, so you still have to go through its class:

my_active_record_instance.class.model_name.singular

or call it directly on the class:

MyActiveRecord.model_name.singular

The ActiveModel::Name instance returned by model_name contains many other inflections and name-related stuff.

You might consider making a module or concern that defines a name_for_path (or something) method, and which you can then include in the relevant models, so you can just call that.

By the way, your solution is not uncommon. I looked at the source for the Paperclip gem, which constructs file paths from model names, and it does pretty much the same thing to get the model's name, (though I don't know if there's a specific reason for it, or if they too could just as well use the approaches above).

However, if you keep your version, you should probably use to_s like Paperclip does:

my_active_record_instance.class.to_s.underscore


Ruby is a departure from PHP. It has a different syntax. Parentheses are often optionally when calling functions. Say you have the following function:

def add(x, y)
    x + y
end

The following are equivalent:

puts(add(3, 5))
puts add(3, 5)
puts add 3, 5

Similarly, these parentheses can be omitted, but only when the arguments are empty. Thus, the following are equivalent:

def hello()
    puts "world"
end
def foo
    puts "bar"
end

hello
foo()

So, as for one of your code examples:

def user_interaction()
  print_delimiter()
  print_status()
  print_action()
end

Can become:

def user_interaction
  print_delimiter
  print_status
  print_action
end

def print_status()
  puts "It's day #{$day}. You have #{$logs} logs and #{$chunks} of chunks."
end

Minor English quibble: it should be #{$chunks} chunks.

  if logs_to_chop > $logs
    logs_to_chop = $logs
  end

You can use a neat feature of ruby's syntax: a single-statement if block shaped like this:

if c
    d
end

Can become this:

d if c

Accordingly, this line could become:

logs_to_chop = $logs if logs_to_chop > $logs

However, this change is to your discretion.

You should move your global variables ($logs, $day, $chunks) to the beginning of your code.

$chunks += logs_to_chop*2

You should always put a space on either side of binary operators like * and +. So, it should become this:

$chunks += logs_to_chop * 2

Your code ends with an exit statement; this is unnecessary, since the program terminates at the end of the program anyhow.

Other than these suggestions, I think your code is really readable. Great job! In larger programs, you may wish to add comments. I don't think they're as crucial here, since the task itself is simple enough.


As for your questions:

Just use int, unless this is critical code where benchmarks have shown that integers are noticeably slower. Furthermore: your char will support 255 vertices which isn't a lot, I've loaded models with millions of vertices.
This level of error checking is possibly an indication that your code smells. You have a function that accepts many parameters, perhaps you can split it into multiple functions or a class type of structure.
Myself, I make everything const unless it cannot be const.
If the size is known at compile time, how about std::array instead of std::vector? As for std::unordered_set it seems too fancy for the job (e.g., a self balancing tree with 3 items, whoop! whoop!), but I have no strong arguments.
No opinion. Myself, I never use C++ exceptions - due to my lack of understanding / education. In other languages I never directly use the build-in Exception types, I always subclass my own - if anything it helps the library user understand if they are library errors or system errors.
You can place your new'ed memory in a std::unique_ptr or use the resize features of std::vector or std::string

Couple more random things:

file.close(); is optional, the std::ifstream will also close the resource (if it was open).
You're not testing for OpenGL related errors.
I don't like 'out' arguments, such as vertexCount. Just return a std::tuple with multiple arguments, or a struct.
Does your file contain binary data? You're reading it from disk, and directly upload it to the GPU without parsing/validation? If anything, make sure you've actually read the amount of bytes that tellg claims are available.
std::ifstream has a constructor, use it.


You can save some time by not running through every counter and setting them to the maximum each time max gets called. Since they are all equivalent at the start and after each time the max is called, you can just record the current maximum counter value (in between each call of max) and add it all together at the end, rather than updating every counter element each time max is called.

let currentTally = {};
let currentMax = 0;
let total = 0;
for (let K = 0; K < M; K += 1) {
        if (A[K] <= N) {
             if(currentTally[A[K]]){
                 currentTally[A[K]] += 1;
             }else {
                 currentTally[A[K]] = 1;
             }
             if( currentTally[A[K]] > currentMax) {
                  currentMax = currentTally[A[K]];
             }
        }

        if (A[K] === N + 1) {
            total += currentMax;
            currentTally = {};
            currentMax = 0;
        }
        }
    }
    for(let i = 0; i < counters.length; i++) {
         if(currentTally[i]){
             counters[i] = total + currentTally[i];
         }else{
             counters[i] = total;
         }
    }

Also, this way, no need to set all counters to zero in the first place.


Listing the representations of integer M as a sum of three squares M = x^2 + y^2 + z^2

You might be interested in this question.

While looking for solution to

$$ x^{2} + y^{2} + z^{2} = M $$

you can assume

$$ x  \leq y  \leq z$$.

and perform rotation if needed afterward.

This is good because, you can start iterating over x in a smaller range. You know that

$$ M = x^{2} + y^{2} + z^{2} \ge x^{2} + x^{2} + x^{2}  = 3 * x^{2}$$

, therefore $$x \le sqrt(M / 3)$$

Similarly, when iterating over y, you can start at xand go up to a smaller higer bound because we have :

$$ M = x^{2} + y^{2} + z^{2} \ge x^{2} + y^{2} + y^{2}  = x^{2} + 2 * y^{2}$$

, therefore $$x \le y \le sqrt((M - x^{2})/ 2)$$

Then, when once x and y are fixed, you don't need to iterate over z : just compute

$$ z = sqrt(M - x^{2} - y^{2}) $$

and check that it is indeed an integer.

Here's a proof-of-concept piece of code : I've altered your code a bit to be able to compare the results you originally had with the one I get :

sq = set(tuple(sorted([i,j, int(np.sqrt(M - i**2 - j**2))])) for i in range(m) for j in range(m) if i**2 + j**2 in y)
print(len(sq))

sol = []
lim_x = int(np.sqrt(M/3))
for x in range(1 + lim_x):
    rem_x = M - x*x
    lim_y = int(np.sqrt(rem_x / 2))
    for y in range(x, 1 + lim_y):
        rem_y = rem_x - y*y
        z = int(np.sqrt(rem_y))
        if z*z == rem_y:
            assert x <= y <= z
            assert x*x + y*y + z*z == M
            sol.append((x, y, z))
print(len(sol))

assert all(s in sol for s in sq)

You have 26 different ordered solutions out of the 290 I found (in a smaller time range).

Finally, you might be able to adapt the equations above (and the code written from it) if you want to handle ranges of M values.


Items derived from one function are getting printed within another for loop in another function

First of all, usual things (I feel like I'm suggesting these things in most of the web-scraping related discussions):

initialize session as requests.Session() and use session.get() instead of requests.get() - this would speed things up because the underlying TCP connection will be re-used for subsequent queries to the same domain
use SoupStrainer to limit what is parsed when the "soup" object is initialized

And, I am not completely sure about the reliability of the .pull_right a selector. At this point, it reads that you want to follow the link that is on the right in its respective container. The position of the element on the screen may easily change with a design change. What about a selector like a[id*=ReadMore] or .more > a?
Also, note that select()[0] could be replaced with select_one().
Code Style
There is not a lot of things to point out since the code is rather short and straightforward, but there are some PEP8 violations that can be addressed:

watch for the use of blank lines
you miss spaces between the function arguments
url should be named URL, since it is a "constant"
use a single # for comments
group imports properly

Some of the variable names could be more explicit, e.g. event_date in place of ev_date, event_link instead of i_link.
The improved code
from urllib.parse import urljoin

from bs4 import BeautifulSoup, SoupStrainer
import requests

URL = 'replace_with_the_above_link'

def glean_items(session, main_link):
    response = session.get(main_link)

    parse_only = SoupStrainer(class_='course-list-item')
    soup = BeautifulSoup(response.text, "lxml", parse_only=parse_only)
    for item in soup.select('.course-list-item'):
        event = item.select_one(".lead").text
        date = item.select_one(".date").text
        link = urljoin(main_link, item.select_one(".pull-right a")['href'])

        parse_more(session, event, date, link)

def parse_more(session, event_name, event_date, event_link):
    response = session.get(event_link)

    parse_only = SoupStrainer(class_="e-loc-cost")
    soup = BeautifulSoup(response.text, "lxml", parse_only=parse_only)
    for items in soup.select('.e-loc-cost'):
        location = ' '.join([' '.join(item.text.split()) for item in items.select(".event-add")])
        cost = ' '.join([' '.join(item.text.split()) for item in items.select(".costs")])

        print(event_name, event_date, location, cost)

if __name__ == '__main__':
    with requests.Session() as session:
        glean_items(session, URL)


Extracting First, Last & Middle Name from a full name

Provide a type for your full_name argument and a more specific type than Object for the return type:

interface SplitNameData {  // Does anybody have a better interface name?
  FirstName: string;
  MiddleName: string;
  LastName: string;
}

ProcessFullName(full_name: string): SplitNameData {
  const Obj: SplitNameData = {
    firstName: '',
    middleName: '',
    lastName: ''
  };

I think it would be cleaner to use null as a marker for non-existing names instead of the empty string even though the empty is probably not a valid name anywhere in the world.
What is your function supposed to do with names having more than three parts?
Consider using const wherever possible and let in all other cases. I recommend to never use var. ⇒ const Obj, const splitName.
Use a more descriptive name for Obj, e.g. splitNameData or separatedNames. In this case, I would recommend to rename splitName to something like nameParts as well to avoid confusion.
Use a consistent naming scheme: fullName instead of full_name, firstName instead of FirstName and so on.
Use array destructuring:

case 2:
  [Obj.FirstName, Obj.LastName] = splitName;
  break;
case 3:
  [Obj.FirstName, Obj.MiddleName, Obj.LastName] = splitName;
  break;

ad performance: for this computationally simple task, any optimization would be premature optimization in my opinion.
Alternative (maybe cleaner?) solution using named RegExp capture groups:

const NAME_PATTERN = /^(?<firstName>[^ ]*) ((?<middleName>[^ ]*) )?(?<lastName>[^ ]*)$/;

const emptyNameData = {
  firstName: '', middleName: '', lastName: ''
};

const {
  groups: {
    firstName,
    middleName = '',
    lastName
  } = emptyNameData
} = NAME_PATTERN.exec(fullName) || {};
alert([firstName, middleName, lastName]);

I am not very keen on the || {} part, maybe an if-else checking the match object for null would be a better solution.


Inject a list of processes to execute using spring DI

This is a learning exercise for me as well so I hope I can be helpful with my answer.

I think you can loose the Configuration class entirely. Add
@Component/@Service annotation to your TextMessageProcessor. Spring should be
capable of figuring out MessageProcessor List wiring on its own. Have you already tried that?

If you are worried about the order of the beans inside MessageProcessor List then you can use @Order annotation on your Service and/or Component.

@Component
@Order(value=1)
public class TextMessageProcessor implements MessageProcessor {
}

Your Configuration class in its current form is conflicting with Open Closed principle. In other words, whenever you add a new MessageProcessor, your configuration will grow. Imagine that configuration after you have 20 processors.
Spring creates qualifier names automatically as your bean names.
From Spring documentation:

  For a fallback match, the bean name is considered as a default qualifier value.

I recommend doing your wiring through constructors instead of fields  (I am especially eyeballing that DAO of yours). That way you preserve an ability to test your code later on. You will need to inject objects through constructors in your tests.
You could move Logging to MessageProcessor if it was an abstract class. Make a field or a method for Logging which returns the logging instance for current class. (Stackoverflow link)


Graph: Depth First Search (N citizens with pairs of friends)

Review of your code

You should mostly prefer the in operator instead __contains__. See @HeapOverflow's comment for more details.

According to PEP 8, you should not prefer CamelCase for variable names. Use snake_case instead.

temp = input().split()
N = int(temp[0])
M = int(temp[1])

Can be replaced with
M, N = [int(x) for x in input().split()]

And the same applies for a similar case.

  counter = 0
  for y in range(N):
      counter += 1
      nodes.append(counter)

nodes is just equal to the values from 1 to N, which is just equal to list(range(1, N+1))
Therefore, you can remove counter completely.

  if index_of_node == 0:
      neighbours.append(edges[j][1])
      hashmap[h+1] = neighbours
  else:
      neighbours.append(edges[j][0])
      hashmap[h+1] = neighbours

Since hashmap[h+1] = neighbours is executed regardless of the if statement, you can move it outside the scope.

def reset_array():
    visited = []
    for _ in range(1, N+2):
        visited.append(False)
    return visited

visited is basically just equal to [False] * (N+1).
The whole function can be replaced to return [False] * (N+1)
Also, this is a personal preference, but you don't have to use a function for this.

Function dfs

next is an inbuilt function's name, and therefore it should be avoided.
neighbours = hashmap[at] Since this is used only once, the assignment is unnecessary
else: return this is unnecessary, as the function does that anyway

Here's how dfs might look after applying the above changes:
def dfs(at):
    global current_group

    if visited[at]:
        return

    visited[at] = True
    current_group += 1

    if at in hashmap:
        for next_ in hashmap[at]:
            dfs(next_)

Faster Algorithm
The dfs will take O(N) time, and since it's executed N times, the time complexity will be O(N^2) which is clearly not feasible.
A disjoint set union on the other hand, will take a lot lesser time.
Here's my accepted code that uses DSU:
for _ in range(int(input())):
    n, m = map(int, input().split())
    dsu = [-1] * n

    for _ in range(m):
        u, v = map(int, input().split())
        u -= 1
        v -= 1

        while dsu[u] >= 0:
            u = dsu[u]

        while dsu[v] >= 0:
            v = dsu[v]

        if u == v:
            continue

        if u > v:
            u, v = v, u

        dsu[u] = dsu[u] + dsu[v]
        dsu[v] = u

    print(-min(dsu))

In case you have any queries about the above code, do ask me in the comments.

Also, I guess you're switching to python from java judging by the fact you named a variable hashmap. If that's the case, welcome to world of python!


Preorder traversal of binary tree to produce formatted string

I haven't fully parsed your code, but I would definitely add a check before creating the root. This get(0) would break on an empty list, and would break on a null list. Or you could throw an IllegalArgumentException as well.


Project Euler # 37 Truncatable primes in Python

You know that a prime other than 2 and 5 ends in 1, 3, 7 or 9. What does that tell you about the digits of x if it is right truncatable? It tells you that all the digits after the first must be 1, 3, 7 or 9.

On the other hand, if you have a four digit left-truncatable number, then the last three digits are also left truncatable. So the find the n+1 digit both left and right truncatable numbers, you take an n digit one which starts with 1, 3, 7 or 9, and prepend any of the digits 1 to 9, and check that the result is both a prime and right-truncatable.


Finding the minimum number of required deletions to have a non-repeating string

Here's your culprit:

del str[j+1]

When you remove one character from a string, all subsequent characters need to be shifted into the hole that you create.  That changes your algorithm from O(Length) to a worst-case scenario of O(Length2), if every character is the same.

Additionally, your inner loop looks a lot like C code.  Here is one way to reformulate it.

def count_consecutive_deletions(s):
    deletions = 0
    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            deletions += 1
    return deletions

def testcases():
    for _ in range(int(input())):
        yield input()

for case in testcases():
    print(count_consecutive_deletions(case))


Concept for PHP Controlled, Privileged Execution (for a cPanel knockoff on Ubuntu Server)

I'd say: go run a gearman daemon as the correct user, and set some gearman workers as priviliged users up with something like supervisord. Both are in the Debian packages, so I assume they'll be in the Ubuntu packages also....

Do set up gearman with a maximum number of tries, or you could encounter a Poison Message problem.


Finding all indices of largest value in an array

In this case, your performance will not be terrible, but, for really large arrays you may run in to problems.

Also, there is a bug in your code... what if the input array is empty? Then you will get an ArrayIndexOutOfBoundsException on:

float largeNumber = numbers[0];

There is always more than one way to do things, but, I want to post an answer here because one possible solution (which may or may not be faster than your solution depending on data size) has a really close relationship to another CodeReview question posted recently. When I answered that question I could only think of artifical examples of when it was 'right' to use pre/post-increments. This is a good example of when....

See this answer here: Is it bad practice to increment more than one variable in a for loop declaration?

So, here is a good example of how and when a count and an index are related in a for loop and the way they can be incremented. I have some notes at the end:

private static int[] findLargeNumberIndices(float[] numbers) {

    // create an array of at least 8 members.
    // We may need to make this bigger during processing in case
    // there's more than 8 values with the same large value
    int[] indices = new int[Math.max(numbers.length / 16 , 8)];
    // how many large values do we have?
    int count = 0;
    // what is the largest value we have?
    float largeNumber = Float.NEGATIVE_INFINITY;
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] > largeNumber) {
            // we have a new large number value... reset our history....
            largeNumber = numbers[i];
            // setting count to zero is enough to 'clear' our previous references.
            count = 0;
            // we know there's space for at least index 0. No need to check.
            // note how we post-increment - this is a 'pattern'.
            indices[count++] = i;
        } else if (numbers[i] == largeNumber) {
            // we have another large value.
            if (count == indices.length) {
                // need to make more space for indices... increase array by 25%
                // count >>> 2 is the same as count / 4 ....
                indices = Arrays.copyOf(indices, count + (count >>> 2));
            }
            // again, use the post-increment
            indices[count++] = i;
        }
    }
    // return the number of values that are valid only.
    return Arrays.copyOf(indices, count);
}

Notes about this code:

The presentation (System.out.println(...)) is now outside the method.
It allocates a 'small' array to store the indexes. This array will grow if needed.
I picked 'good enough` initial size for the array.... but some playing with the numbers may help performance.
There is no real reason to believe that this code is faster than the two loops - creating the array may be more expensive than the second loops.
note how the i index is incemented in the for-loop, but the `count` is post-incremented each time it is used in the array.


First, remove import play.api.libs.concurrent.Execution.Implicits._. You don't want the default Play execution context. Instead, you should use one of the ExecutionContexts you've defined and aren't using. Perhaps define one for S3 operations alone, and you don't need the others if you aren't going to use them. Future.apply requires the implicit ExecutionContext, so you can either import the correct one, or explicitly pass it.

Assuming you have a context defined like this in your configuration:

contexts {
    s3-ops {
        fork-join-executor {
            parallelism-factor = 10.0
        }
    }
}

Then in your controller you could add:

implicit val ec: ExecutionContext = Akka.system.dispatchers.lookup("contexts.s3-ops")

Now in the body of the controller function, I'll work my way inward. With the handling of the session, why bother returning data to the user if they don't have a session? It would seem more appropriate to return Forbidden, which can shorten that line to Future.successful(Forbidden). Note that Future.successful creates a Future that has already been completed.

The use of try/catch is not very Scala-like. There are other nicer ways to handle errors in Scala like Try. Future is actually very similar to Try, though, and it should provide all the error handling you need in this case. If an exception occurs within a Future, then it becomes a failed Future. No exceptions will propagate upward. Most of the code inside your try block can go inside the Future apply instead.

var videoName: String = null is something that should be avoided altogether. First, it's best to avoid mutable vars, and second you should never find yourself assigning null to anything.

I'm not sure the body of your current Future where you're mapping request.body.files is doing what you think it's doing. request.body.files is a Seq[FilePart], which means if there are multiple FileParts, you're going to upload them all separately, overwrite videoName and only return the name of the last uploaded FilePart. Or worse, if there are no FileParts, that part will silently fail. If you're only going to have a single FilePart, it'd be better to name it in the upload body and access via request.body.file("filename") which will be an Option[FilePart]. From there you can map the Option[FilePart] to the actual upload.

Since you're not actually doing anything with the PutObjectResult from the S3 response, it'd be better to return the name of the file in the Future, so that you have access to it when you map the Future, and would no longer have a need for a var. Following the suggestions above, it would now be a Future[Option[String]].

This would leave you with three return states for the Future:

A successful Future containing Some[String] (upload success on both ends).
A successful Future containing None (no file was uploaded to the server).
A failed Future (the upload to S3 failed somehow).

You'd then have something that looks roughly like this:

Future {
    request.body.file("filename").map{ file =>
        val videoName = ...
        amazonS3Client.putObject(...)
        videoName
    }
}.map{ upload =>
    upload.map{videoName => Ok(...)}.getOrElse{BadRequest(...)}
}.recover{ case _ =>  // recover the failed `Future` to a default value, in this case a `Result`
    InternalServerError
}

Much cleaner. Note that recover accepts a PartialFunction[Throwable, ?], similarly to a catch block, so you can be more fine grained in your error handling if you need to.

A couple more notes:

There's no need to use Lift's json API for your responses. Play's implementation works just fine:

import play.api.libs.json.Json
Ok(Json.obj("result" -> "success", "videoName" -> videoName))

Your imports take up a lot of space. Many can be condensed into one liners:

 import play.api.i18n.Lang
 import play.api.i18n.Messages

Can be:

 import play.api.i18n.{Lang, Messages}


Create a summary report by summing the amount's of accounts with the same name and within the date range specified

The kind of operation you’re doing is called a join: you want to associate data from a DataFrame to data from another one based on a shared information on a given column.

To join a DataFrame to another one or to a Series, you need to respect a simple rule: either you join on index or a column is joined to an index; and they must be of similar nature. So in your case, since you need to join on the name of the account, one of your DataFrame must be indexed by this name. Since it is its purpose, you need to reindex data_listofaccounts by its 'Account Name' column:

data_listofaccounts = pd.read_csv(listofaccounts_csv)
data_listofaccounts = data_listofaccounts.set_index(['Account Name'])

Then, before joining, you can filter out data that is out of your study range so the join is performed on less data:

filtered = data_entries[(start_date <= data_entries['VOUCHER DATE']) & (data_entries['VOUCHER DATE'] <= end_date)]

And thus the data you’re interested in is accessed using:

data_entries = pd.read_csv(entries_csv)
data_entries['VOUCHER DATE'] = pd.to_datetime(data_entries['VOUCHER DATE'], format="%m/%d/%Y")
data_listofaccounts = pd.read_csv(listofaccounts_csv)
data_listofaccounts = data_listofaccounts.set_index(['Account Name'])

start_date = datetime.date(2018, 4, 1)
end_date = datetime.date(2018, 10, 30)
date_mask = (start_date <= data_entries['VOUCHER DATE']) & (data_entries['VOUCHER DATE'] <= end_date)
interesting = data_entries[date_mask].join(data_listofaccounts, on='DEBIT ACCOUNT')

And then each row of interesting will have all the information needed: the transaction date, the name of the account, its type and the amount spent.

But this is all without taking into account the kind of operations you want to perform afterwards: grouping by name and summing the amounts. You can perform this operation directly before joining and it will simplify the process altogether:

data_entries = pd.read_csv(entries_csv)
data_entries['VOUCHER DATE'] = pd.to_datetime(data_entries['VOUCHER DATE'], format="%m/%d/%Y")

start_date = datetime.date(2018, 4, 1)
end_date = datetime.date(2018, 10, 30)
date_mask = (start_date <= data_entries['VOUCHER DATE']) & (data_entries['VOUCHER DATE'] <= end_date)

amount_per_account = data_entries[date_mask].groupby(['DEBIT ACCOUNT']).sum()

This will return a DataFrame indexed by the accounts names whose 'DEBIT AMOUNT' column is the sum of each row pertaining to this account. You then just need to join with data_listofaccounts to know if this sum should be positive or negative based on the 'PARENT NODE' column.

summary = data_listofaccounts.join(amount_per_account, on='Account Name', how='outer').fillna(0)
debit_mask = (summary.Type == 'CURRENT LIABILITY') | (summary.Type == 'LONG TERM LIABILITY') | (summary.Type == 'EQUITY')
summary[debit_mask]['DEBIT AMOUNT'] = -summary[debit_mask]['DEBIT AMOUNT']

Other improvements pertaining to coding style:

you should define functions to organize your code
you should guard your code using if __name__ == '__main__'
you don't need to say that a variable contain some data_; same for namming a collection, you don't need to say what kind of collection hold the data (besides, in your case it is misleading as your listofaccounts is in fact a DataFrame); so data_listofaccounts => accounts
you should follow PEP8 namming conventions

And to pandas:

you can limit the amount of data retrieved from your CSVs by using the usecols argument; this will lead to less data manipulation afterwards and thus more speed.


Writing an interface for networking in an embedded system

Just a small note on sleeping when waiting for input.  As others have said
your loop is inefficient in that it uses a simple busy loop.  This has at
least two potential problems:

it prevent other activities from executing;
it uses power.

But these are not necessarily problems for your application.  And if in
your application there really is nothing else to be done until bytes arrive
and if power consumption is not a problem, then a busy loop is by far the
simplest solution.

Using interrupts will inevitably complicate the rest of your code and should
be avoided unless really necessary (for example if there are other
computing tasks that need to run while waiting for input).

If 1 above is not important but 2 is (ie if you need to minimise power use)
you could put the core to sleep during waiting and have the byte-receive wake
it.  This would retain the benefit of avoiding interrupt handling. You would
need to set a timer to wake the core too if you need a timeout.

On the details of your code, I dislike the use of Windows types in an embedded
system.  What is wrong with int and char or their unsigned varieties?

Your leading underscore on _data is reserved by something or other and is anyway
pointless.

I don't object to passing in a void * (after all, C stdlib functions recv
and read do this), but I would assign it to a local variable of appropriate
type and avoid casts.  This makes absolutely no difference when the buffer is
used just once, as here and is just a personal preference.

And using continue is usually frowned on and often unnecessary.

int ReceiveData(void *data, int length)
{
    unsigned char *p = data;
    int received = 0;
    int retry = 0;

    while (received < length)
    {
        if (UART1_Data_Ready())
        {
            p[received++] = ReceiveByte();
        }
        else if (++retry <= RECEIVE_RETRY_COUNT)
        {
            Delay_ms(RECEIVE_TIMEOUT/RECEIVE_RETRY_COUNT);
        }
        else break;
    }
    return received;
}


There are a few things we could improve:

you could use the "lazy" glob.iglob() to filter out *.txt files instead of doing the os.listdir(), keeping the whole list if memory and having an extra check inside the loop:

for filename in glob.iglob("*.txt"):

instead of using textfile.readlines() and read all the lines in a file into memory, iterate over the file object directly in a "lazy" manner:

for line in textfile:

instead of manually keeping track of column value, you could use enumerate():

for column, filename in enumerate(glob.iglob("*.txt"), start=1):

Same idea could be applied for rows.
I think you don't have to use get_column_letter() and instead operate the numbers which you have:

sheet.cell(row=row, column=column).value = line

not to say anything against openpyxl, but I personally find xlsxwriter module's API more enjoyable and more feature rich

Complete improved version:

import glob

import openpyxl

def text_into_spreadsheet():
    """main logic for read .txt into spreadsheet"""
    workbook = openpyxl.Workbook()
    sheet = workbook.active

    for column, filename in enumerate(glob.iglob("*.txt"), start=1):
        with open(filename) as textfile:
            sheet.cell(row=1, column=column).value = filename

            for row, line in enumerate(textfile, start=2):
                sheet.cell(row=row, column=column).value = line

    workbook.save('result.xlsx')

if __name__ == "__main__":
    text_into_spreadsheet()


Retrieving access token from SharedPreference

ClassCastException is not a checked exception, and so it's not a normal practice to catch it. You can omit catching this exception. However, you should make sure your application will never store values in shared preferences that would raise such errors.


Hangman game with hard-coded word or phrase

The first thing that nearly jumps out at me is this:

std::string updateWrongGuesses(const char guess, std::string const& word, std::string wrongGuesses)
{
    return wrongGuesses += guess;
}

It's not at all clear why you pass word to this at all, since it doesn't use or modify it. Worse, it looks like it's actually more work to call the function than to re-implement what (little) the function does. At least to me:

wrongGuesses += guess;

...seems simpler and more readable than:

 wrongGuesses = updateWrongGuesses(guess, word, wrongGuesses);

I think I probably would use a class (or possibly two) in writing this code. My first attempt would be something on this general order:

#include <iostream>
#include <string>

class hangman{
    static const int max_wrong = 8;
    std::string word;
    std::string display;
    std::string wrong;
public:
    hangman(std::string const &word) : word(word) {
        for (char ch : word)
            display += isspace(ch) ? ' ' : '*';
    }

    void enter_guess(char ch) {
        bool correct = false;

        for (std::string::size_type i = 0; i != word.size(); ++i)
            if (word[i] == ch) {
                display[i] = ch;
                correct = true;
            }
        if (!correct)
            wrong += ch;
    }

    bool is_over() {
        return wrong.size() == max_wrong || display == word;
    }

    std::string final() {
        return "The word was: " + word + (display == word ? "\nYou win!" : "\nYou lose");
    }

    std::string status() {
        return "\nwrong guesses: " + wrong + "\nCurrent word: " + display;
    }
};

char get_guess() {
    std::cout << "Please enter your guess: ";
    char ch;
    std::cin >> ch;
    return ch;
}

int main()
{
    hangman game("rabbit rabbit");

    do {
        std::cout << game.status() << "\n";
        game.enter_guess(get_guess());
    } while (!game.is_over());
    std::cout << game.final();
}

As far as how much of your code is in main: I try not to treat main any differently from any other function. IMO, you shouldn't strive for main to be as small, or large, or anything else in particular as possible. Rather, main should be a function just about like any other. It should have accomplish something useful. Like any other function, it should have a clearly defined level of abstraction at which it operates, and (for the most part) it should try to stick to it.

As a natural consequence of being bigger, a bigger program will typically have more layers between main and the lowest levels of manipulation, so in a large program it'll typically have little code beyond creating objects and/or calling functions. I wouldn't consider that a particularly worthy goal in itself though. If it fits well with the size and type of program you're writing great--but there's not necessarily a good reason to force it if it doesn't happen to fit or work out well that way.


Rails controller action methods corresponding to static web pages

You don't need to define empty actions in your Controller.

Your code should work even if you delete all the empty actions, leaving you only with the views and routes:

page_controller.rb:

class PageController < ApplicationController
end

views:

adventure.html.erb
cooking.html.erb
dancing.html.erb
programming.html.erb
reading.html.erb
running.html.erb
sports.html.erb
writing.html.erb

routes:

match '/adventure', to: 'pages#adventure', via: 'get'
match '/cooking', to: 'pages#cooking', via: 'get'
match '/dancing', to: 'pages#dancing', via: 'get'

match '/programming', to: 'pages#programming', via: 'get'
match '/reading', to: 'pages#reading', via: 'get'
match '/running', to: 'pages#running', via: 'get'
match '/sports', to: 'pages#sports', via: 'get'
match '/writing', to: 'pages#writing', via: 'get'

or, if you really want things super DRY:

%w(adventure cooking dancing programming reading running sports writing).each do |page|
  match "/#{page}", to: "pages##{page}", via: 'get'
end


Food for thought:
From my (now deleted) comment:
Your operators are associative, but your data structure is not. Is there a different data representation which is associative?
I think you want to do more with this tree than just printing it, right?
The problem is you want Q Unit (Q Unit Unit) to be equal to Q (Q Unit Unit) Unit. Find a 'canonical' representation!
Think about an answer or scroll down to find mine. The next steps just set it up.
Pulling out the operator?
You've already seen this in the comment:
data Operator = ExclamationMark | QuestionMark
data Tree = Unit | BinaryNode Operator Tree Tree

Type parameters
Your example seems to be a minimal working example, but you certainly want your Unit to contain some identifier, e.g. data BinTree a = Leaf a | BinaryNode Operator BinTree BinTree. Do the same with Operator and you've got:
data BinTree op a = Leaf a | BinaryNode op (BinTree op a) (BinTree op a)

Based on your haskell experience, you might want to write your Functor, Applicative, Monad and Traversable instances.
The type parameter op can be instantiated with Operator, but maybe also String in the context of (pretty-)printing. Or go further and have a function in place of op:
evalBinTree :: BinTree (a -> a -> a) a -> a
evalBinTree (Leaf x)                  = x
evalBinTree (BinaryNode f left right) = f (eval left) (eval right)

of course get yourself a function to make these tasks easier:
mapOp :: (op -> op') -> BinTree op a -> BinTree op' a

Associativity Hint
data Binary a = Binary a a is isomorphic to a pair (a,a), which always contains two as. What data structure allows you to have an arbitrary number of as? Next section is some sort of filler to hide the solution.
Haskell philosophy
Haskell is a functional language. While "functional" puts the emphasis on functions, it is actually data-centric. Defining new data structures and converting between them is easier and more concise than in, say, Java. What I am trying to say here: You can keep the BinTree and the AssocTree of the following section and write functions that transforms one representation to the other.
Associativity Solution
First a non-parametric data type that allows an arbitrary number of children:
data AssocTree = Unit | Node [AssocTree]

but I will continue with:
data AssocTree op a = ALeaf a | ANode op [AssocTree op a]

And left as an exercise, you want a function:
toAssocTree :: BinTree op a -> AssocTree op a

But toAssocTree cannot collect your associative operators. That needs equality on op:
collectAssoc :: (Eq op) => AssocTree op a -> AssocTree op a

This way, you divide your computation into little steps.
Why turn Operator into a type parameter op
Here is the reason why I supposed to make the operation a type parameter: With an abstract type, the type system prevents this error:
data BTree = Unit | E Tree Tree | Q Tree Tree
data ATree = AUnit | AE [Tree]  | AQ [Tree]
toATree (E left right) = AE [left,right]
toATree (Q left right) = AE [left,right] -- c&p error: should be AQ, not AE

Yes, abstracting out the type prevents errors.


"Smallest Multiple" is, in other words, the least common multiple of a range of numbers. The function below implements the least common multiple, lcm:

var lcm = function (a, b) {
    // lcm is defined as:
    // lcm(a, b) = abs(a * b) / gcd(a, b)
    if (isNumber(a) && isNumber(b)) {
        if (!isInteger(a) || !isInteger(b)) {
            throw new Error('Parameters in function lcm must be integer numbers');
        }
        return (Math.abs(a) / gcd(a, b)) * Math.abs(b);
    }
};

The helper functions isNumber and isInteger are as follows:

var isNumber = function(value) {
    return (value instanceof Number) || (typeof value == 'number');
};

var isInteger = function(value) {
  return (value === Math.round(value));
};

Ok, so now we have to implement gcd, the greatest common divisor. Here we can use Euclidean Algorithm:

var gcd = function (a, b) {
    if (isNumber(a) && isNumber(b)) {
        if (!isInteger(a) || !isInteger(b)) {
            throw new Error('Parameters in function gcd must be integer numbers');
        }

        // http://en.wikipedia.org/wiki/Euclidean_algorithm
        while (b != 0) {
          r = a % b;
          a = b;
          b = r;
        }
        return (a < 0) ? -a : a;
    }
};

Now that we have lcm, we'll use the fact that lcm(a,b,c) ≡ lcm(lcm(a,b),c) to make the smallestMultiple function:

var smallestMultiple = function (endOfRange) {
    if (isNumber(endOfRange)) {
        if (endOfRange <= 0) {
            throw new Error('Parameter in function smallestMultiple must be greater than zero');
        }
        if (!isInteger(endOfRange)) {
            throw new Error('Parameter in function smallestMultiple must be a positive integer');
        }
        // Observing that lcm(a,b,c) ≡ lcm(lcm(a,b),c)
        var a = 1;
        for (var i = 1; i <= endOfRange; i++) {
            a = lcm(a, i);
        }
        return a;
    }
};

The full code is as follows:

var isNumber = function(value) {
    return (value instanceof Number) || (typeof value == 'number');
};

var isInteger = function(value) {
  return (value === Math.round(value));
};

var gcd = function (a, b) {
    if (isNumber(a) && isNumber(b)) {
        if (!isInteger(a) || !isInteger(b)) {
            throw new Error('Parameters in function gcd must be integer numbers');
        }

        // http://en.wikipedia.org/wiki/Euclidean_algorithm
        while (b != 0) {
          r = a % b;
          a = b;
          b = r;
        }
        return (a < 0) ? -a : a;
    }
};

var lcm = function (a, b) {
    // lcm is defined as:
    // lcm(a, b) = abs(a * b) / gcd(a, b)
    if (isNumber(a) && isNumber(b)) {
        if (!isInteger(a) || !isInteger(b)) {
            throw new Error('Parameters in function lcm must be integer numbers');
        }
        return (Math.abs(a) / gcd(a, b)) * Math.abs(b);
    }
};

var smallestMultiple = function (endOfRange) {
    if (isNumber(endOfRange)) {
        if (endOfRange <= 0) {
            throw new Error('Parameter in function smallestMultiple must be greater than zero');
        }
        if (!isInteger(endOfRange)) {
            throw new Error('Parameter in function smallestMultiple must be a positive integer');
        }
        // Observing that lcm(a,b,c) ≡ lcm(lcm(a,b),c)
        var a = 1;
        for (var i = 1; i <= endOfRange; i++) {
            a = lcm(a, i);
        }
        return a;
    }
};

The main point of everything above is not to talk to you about efficiency of how to handle larger numbers, but it's about something much more important, especially for beginners such as you and I: abstractions.

To abstract means to give names to things, so you can refer to them as a unit. For example, "stir", "fry" and "boil" are abstractions. Which one is better: "stir for 10 minutes, fry the steak and boil the water" or "move the spoon inside the pot for 10 minutes, heat a little oil on a fridge and put the steak on it, and bring the water to a temperature of a 100 degrees Celsius"? Note that the former is more descriptive even though it's less detailed. Similarly, defining smallestMultiple as the lcm of a range of numbers is more helpful than your ad hoc procedure. When you get a job as a programmer, remember that abstractions are king, and that premature optimizations are the root of all evil.

Also, sorry if the validations were excessive or unclear, as javascript is not my primary language and it's combination of dynamic and weak typing makes me a little afraid of it.


Naming.
N_S_G_Lights could be called NorthSouthGreenLights, but that wouldn't make it a much better name. Method names should start with a verb, they do something.
However, the pattern is consistent, which is a good thing. It's redundant though.
Structure.
The things you need to do depend on the vocabulary you're writing your code with - methods are verbs, classes are subjects. Classes are definitions for objects, which encapsulate a piece of functionality and abstract away the implementation details.
The first object I'd think of a design for, would be some TrafficLight class. I'd want the UI code to only have to be told what color that traffic light is, and draw the appropriate background color in that PictureBox.
The form code doesn't need to know about a Timer - it needs to know about a TrafficLight, and from that object it needs to know the LightColor, and it needs to be notified whenever the color changes.
I'd be expecting something like this in a class called TrafficLight:
Private Const RedSeconds As Integer = 31
Private Const GreenSeconds As Integer = 26
Private Const YellowSeconds As Integer = 3

Private LightTimer As Timer 'ticks every second

Private CurrentColor As Color

Public Event Changed(ByVal NewColor As Color)

I like that you have a single timer for the whole 60-second cycle, but the magic numbers  in Lights() make it hard to correlate what you've done with what the requirements are. Using constants as above, helps making the code more readable. The fact that your logic relies on UI values isn't very nice, too.
When you have a TrafficLight that raises an event that says "Hey there, if it's of any interest to you, I'm changing my current color right now" to your form, the form itself doesn't know how the TrafficLight operates, but it knows that when color changes, it needs to change the background color of some PictureBox:
Private Sub NorthSouthLight_Changed(ByVal NewColor As Color)

    NorthTrafficLightPicture.BackColor = NewColor
    NorthLabel.BackColor = NewColor

    SouthTrafficLightPicture.BackColor = NewColor
    SouthLabel.BackColor = NewColor

End Sub

Private Sub EastWestLight_Changed(ByVal NewColor As Color)

    EastTrafficLightPicture.BackColor = NewColor
    EastLabel.BackColor = NewColor

    WestTrafficLightPicture.BackColor = NewColor
    WestLabel.BackColor = NewColor

End Sub

What color that is, isn't important - it's conveyed by the Changed event, if a TrafficLigth wanted to be Blue, the form would happily comply.

TL;DR: In other words, I think your code could greatly benefit from a little bit more of an Object-Oriented approach, especially if this code is vb.net (I was assuming vba all along, when I came across a Handles keyword, which I haven't seen used in VBA).


Project Euler 28 - Number Spiral Diagonals

from timeit import default_timer as timer

start = timer()

This line of code belongs with the code at the end of the program that times the call to spiral_diag_sum.

def spiral_diag_sum(n):

It's always a good idea to add a docstring. Several of the later Project Euler problems rely on finding a solution to earlier ones (though perhaps not this one), so you'll find yourself building up a library of useful code to reuse, in which case a good docstring makes it much easier to import.

    if n < 1: return None
    elif n == 1: return 1
    elif n % 2 == 0: return None
    else:

Checking that your arguments are sane is good. However, here you've got (in sequence) an error condition, a successful return, an error condition and (following the else) the main body of the function. It's better to separate the error conditions and handle them first.

You're also returning None as the error value, but you're not checking for that value after you call spiral_diag_sum at the end of the program. Add code to check that, or better yet, raise an exception here indicating the error. Since both the n < 1 and n % 2 == 0 clauses are checking the same argument's validity, you can combine them into one if-statement:

    if n < 1 or n % 2 == 0:
        raise ValueError("argument must be an odd-valued integer >= 1")

Resuming with the if n == 1: return 1 from the original code:

    if n == 1:
        return 1

Even when it's a short piece of code like here, I like to keep separate statements on their own line. Most Python code that you see will do that.

    else:
        numbers = [1]
        while len(numbers) < (2*n - 1):
            increment = int(len(numbers) * 0.5 + 1.5)
            for p in range(4):
                numbers.append(numbers[-1] + increment)
        return sum(numbers)

The formulas here need more thought than is required. Calculate and store the (2*n -1) formula in a variable with a descriptive name. The increment starts at 2 for the first row out from the center, and goes up by two for every subsequent row, so this whole thing could be:

        numbers_needed = 2 * n - 1
        increment = 2
        while len(numbers) < numbers_needed:
            for p in range(4):
                numbers.append(numbers[-1] + increment)
            increment += 2
    return sum(numbers)

This other answer already explains about the downsides of using a list to hold all the numbers and shows how to calculate the number at each corner. You can go even further and derive a mathematical formula for the total contributed by the four corners of an NxN square, then use that formula iterating from the central 1x1 square out to the final NxN.

   Hint: the last corner of an NxN square will have the value N2. The values of the other three corners can be derived from that value. The same formula also works for the central 1x1 square so you don't even need to have a special case for it.

ans = spiral_diag_sum(1001)
elapsed_time = (timer() - start) * 100 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)

Following from some things I mentioned earlier: making this into a module that you can use in later problems, checking for a valid return value from spiral_diag_sum, and keeping all the timing code together:

if __name__ == "__main__":       # Allows standalone use or as a library module.
    start = timer()              # This code moved from above.
    ans = spiral_diag_sum(2)
    elapsed_time = (timer() - start) * 100 # s --> ms
    if ans:                      # Check for valid answer (or use try / except)
        print "Found %d in %r ms." % (ans, elapsed_time)
    else:
        print "No answer returned"


Some small remarks:

according to the documentation, you want to output irst-fay on first, but your code will output irstf-ay instead

your code will only work on lower case words, but not on "Apple"

instead of print!("{} ", format!(...)) use print!(...)

instead of nth(0) use next()

I recommend you to format your code with rustfmt

instead of &word[word.chars().next().unwrap().len_utf8()..] you can use c.len_utf8() if you name your match instead of using _, e.g.
match word.chars().nth(0).unwrap() {
     'a' | 'e' | 'i' | 'o' | 'u' | 'y' => print!("{}-hay ", word.trim())),
      c => print!("{}-{}ay ", &word[c.len_utf8()..].trim(), c),
};

if you know that your index will end up at a proper UTF8 boundary you can use &word[1..] and &word[..1] instead of your indexing, but your variant is a lot safer. Well done here, as invalid string slicing is a common error in first Rust experiences :)


Making multiple calls to API and processing data in Node.JS

Looking for sensitive terms

I see that you build a regex from a list of terms:

  var danger = ['password','pass','pw','pwd','passwd','key','user','username','secret']
  var re = new RegExp(danger.join('|'))

With this approach,
some of the items in danger are redundant,
because "password" and "passwd" will be already matched by "pass",
"pwd" will be already matched by "pw",
and "username" will be already matched by "user".

Overall this approach looks rather primitive and I suspect it will yield too many false positives to be useful.

Duplicated calls

In this code contents.match(re) is executed twice:

  matches = contents.match(re)
  if(matches.length > 0){
    // console.log("matches", matches)
    review = review.concat(contents.match(re))
  }

That's a waste, it would be better to use matches in place of the second call.

Truthy values in JavaScript

Non-empty arrays are truthy, so instead of if(matches.length > 0) you could write simply if (matches.length), and even just if (matches).
The same goes for if(results.length > 0) later in the code.


Layout for code:
Look at PSR spec: http://www.php-fig.org/psr/psr-2/

for comments:
https://www.phpdoc.org/docs/latest/getting-started/your-first-set-of-documentation.html#writing-a-docblock

Finally is your code testable and possibility to extend without modifying it?

Also "(static) $instance" doesn't feel right to me for some reason, try different name?


Again enums should not have any prefix. Drop all those Enum_! You may like to take a look to .NET Naming Guidelines.

Inside the class UserEventLog you do not need to repeat Log prefix for its properties. For example just Message is enough. Think about a Window object: did you ever see properties named WindowTitle, WindowSize, WindowCanMaximize and so on?

Validate values, I might assign null to LogMessage (or an invalid enum for EventType) and it will go straight to the DB engine (which might reject it or not).

Do not hide resolved services in a property like UnitOfWork and UserEventLogService. If you use those objects more than once in the same call then it's a performance hit you do not want to pay (because it has to be resolved for each call and it might event be a new object, it depends on how it's configured in your DI framework). Resolve them once in ctor or better accept them as parameters.

In addition of a single method Log() with all those parameters you may want to introduce few extension methods (or overloads):

public static async Task LogUserWarning(this EventLogger logger,
                                        DateTimeOffset eventTriggeredOn,
                                        string eventName,
                                        string message)
{
    // ...
}

Think twice before using default values for parameters. If you own this code and the calling code then it's not an issue (probably) but if your code is released as a library, to be used by someone else, then you're introducing a strong contract (simply changing default value will not update callers unless they're recompiled, not to mention that they have to check if new values are what they expect). For a real-world example of this issue you may read Adding option parameter to a library in c# without creating a breaking change
.

Using String.Empty instead of null for a string entry in a DB may be a waste but it depends on DB engine you're using (for example compare SQL Server and Oracle).

I see no reason for EventLogger to do not be sealed.

Do not use System.Web.HttpContext.Current directly. Accessing a static property makes impossible to test your code in unit testing outside an HTTP request. The same is true for GetLocalIPAddress(). If really you can't avoid it then move it to a derived class, at least you can test all the underlying logic in isolation. Better would be to introduce a service to retrieve those information:

interface IHttpRequestInspector
{
    string GetIpAddress();
    string GetAuthenticatedUserName();
}

Now you can create a default implementation using the code you already have but you can also have a MockedHttpRequestInspector class which can be used in unit testing:

sealed class MockedHttpRequestInspector : IHttpRequestInspector
{
    public MockedHttpRequestInspector(string ipAddress, authenticatedUserName)
    {
        _ipAddress = ipAddres;
        _authenticatedUserName = authenticatedUserName;
    }

    public string GetIpAddress() => _ipAddress;
    public string GetAuthenticatedUserName() => _authenticatedUserName;

    private readonly string _ipAddress;
    private readonly string _authenticatedUserName;
}

Some properties you declared in UserEventLog are not used in code you show (for example UserEventLog.User). Drop them?


Converting Integer to dynamically allocated Char array, digit by digit using pointers

Issues Concerning Allocation
It is not necessary to cast the result of a call to malloc() in C, and many consider this to be a more error-prone style. It is easier to write correctly, read, and maintain the allocation line if you write it like this:
char *numberAsString = malloc(sizeof(*numberAsString));

This way, if the type is changed at some point in the future, there is only one place you need to update, versus three places to update in your version.
I would also suggest moving the allocation from main() into the intToStr() function (which is already reallocating the memory), and returning a pointer to the allocated memory to the calling function. This would necessitate changing the function signature of intToStr() to:
char * intToStr(int myNumber, char* myString);

Then in main(), you should declare:
char *numberAsString = NULL;

The same advice given above for malloc() applies to the calls to realloc() in the function intToStr(). Additionally, realloc() returns a NULL pointer in the event of an error. By assigning the return value directly to myString you risk leaking memory by losing the pointer to the previous allocation. You should store the return value of realloc() in a temporary variable, and then assign it to myString if it is non-null.
Continuing with allocation issues, I would consider mallocing enough memory to hold any int number-string (really, I would suggest using an int32_t number-- see below) at the beginning of intToStr(). Then, before returning the pointer to this memory, you can realloc() to the size of the actual number-string, i.e.:
number_string_sz = 12;  // for int32_t plus space for `-` and `\0`

myString = malloc(number_string_sz);

...

temp = realloc(myString, strlen(myString) + 1);
if (temp) {
    myString = temp;
}

You may wish to return a NULL pointer from intToStr() if there is an allocation error, and let the caller handle the error. Of course, the caller is responsible for freeing allocated memory.
Integer Overflow
Note that it is possible that myNumber is equal to INT_MIN, and then the line myNumber *= -1; would lead to integer overflow (invoking undefined behavior for signed integer types). Consider using a fixed-width type, such as int32_t, that is passed into the function, and copy this to a larger fixed-width type (int64_t) for a working copy within the function. The reasoning here is that the widths of the integer types are implementation-dependent, and even long int is only guaranteed to be at least as wide as int. By choosing specific widths for your integer types, you can protect against integer overflow in your calculations. The int64_t type is larger than int32_t, so the smallest value which can be held by an int32_t, when stored in an int64_t, can safely be multiplied by -1.


I don't know that my code is vulnerable to SQL injection.

Yes, it is.

You should never put any variables directly into SQL statements. Even if you think that the variables may possibly be safe, it's just really bad practice, and you will mess it up sooner or later. In your case, an attacker could use the profile fields, which would very likely lead to SQL injection (this depends a bit on the input filter for the profile fields, but I would be surprised if it caught all injections, and you should definitely not rely on it).

  Should I have to use prepared statements and rewrite the code.

Yes. Prepared statements are the only reliable way to prevent SQL injection, and you should never write any SQL statements without prepared statements. It is bad style and very insecure.

Misc

You really don't want to display errors in production.
You have too much vertical whitespace.
Some may disagree, but 2 spaces for indentation makes code harder to read. If you need this because your code is too nested, remove some levels of nesting instead of removing indentation.
functions.php is quite a generic name. It also doesn't fit it's content at all. As it contains a class, it should have the same name as the class (possibly with .class added).
You should create your database connection only once, and then pass it to the functions needing it, instead of creating a new connection for each object needing it.
don't shorten variable names, just write them out.
don't die in functions, it makes it hard for the calling code to handle.


Splitting std::string based on delimiter using only find and substr

Bug

If the original string doesn't have trailing delimiter, the code leaves out the last token.

Unqualified calls

Unqualified call is any function call which doesn't have preceding ::. People oppose using namespace std;. In my opinion, it is not as much of a problem if done carefully (for small programs or at function/block scope). What is dangerous though, is unqualified call. It can be very evil. Anyway, my recommendation is to just type std:: unless you want to have a fallback into standard library functions at the current scope. I know this sounds confusing, but may be as time passes by it will become clearer.

Formatting

There are formatting conventions many people use to make code readable among themselves. Sometimes it helps to understand control flow, templates, pointers, etc. I don't have any strong opinions on any particular one though, as long as it is consistent. Formatting the code in question used is rather unusual. I use snake_case, for everything except template parameter names and concepts. The more common version though is CamelCase for type names and camelCase for variable names, functions. ALL_CAPS are reserved for macros, as they're quite evil.

Accepting by value

Although sometimes it makes sense, in the case shown in question, it doesn't. When something is used for read-only purposes, pass by const T&. In this case, it might even make sense to take by std::string_view. At the moment the code copies the arguments, which may be very costly if strings are big.

Peculiar way of looping

count and i are at the moment sort of a flag, either true or false (it takes many values, but squashing i and count into one would produce the flag). It would be better to loop until find returns npos.

size_t

For indexing, size_t is usually used. Some people prefer ptrdiff_t. The advantage they have over int is that they will as big as indexable memory is (though max of ptrdiff_t might be less that max of size_t). int might not be big enough in some cases.

Small stuff

Use const auto& if looping in read only mode (for (const auto& e: x)).

return 0 is redundant.

Don't use std::endl unless immediate printing is necessary. An example of immediate printing can be real-time games, where users need to see output immediately.

Don't put extra () anywhere unless compiler doesn't understand you. Most of the time they are redundant, in worst cases they produce bugs and dangling references.

My approach

I'm a lover of standard library algorithms. Here is a good  talk to give a starter if you know basic algorithms (Disclaimer: I'm not familiar with the speaker, though ACCU is a good conference).

Lets develop the algorithm first.

prev_pos <- start of the string
next_pos <- next delimiter location in string
if next_pos is end of the string, go to 7
append {prev_pos, next_pos} to results
increase prev_pos by next_pos + delimiter.size().
Go to 2.
if prev_pos is not end of the string, add the remaining portion of the string to results.

(This is a very bad parody to Knuth's style)

From the algorithm, it is already clear that the variables prev_pos and next_pos are not well named. I left it out as example, to demonstrate when variables could be given a good names. Good algorithm is complemented by good names, and sometimes staggered by bad ones.

Now the implementation. When starting out with a language, it is very hard to find direct equivalent to actions in the algorithm. Fortunately, C++ allows coming close to it, though building blocks are in the standard library already. I recommend using some good, up-to-date documentation. I use cppreference.com .

The first step is understanding iterators. I don't really have a good reference for them, but iterators are the glue that binds containers and algorithms in C++. For now, let's assume it is a pointer into the string. Every standard library container has begin() and end(). The former is iterator to the beginning of container, and the latter is one past the end iterator. In case of "word", begin would point to w, and end to whatever is after d.

The algorithm that searches for the occurrence of a sequence in a bigger sequence is std::search(). If "very long string" is std::searched for "string", it will return iterator pointing to s.

std::vector has emplace_back(), which constructs element in-place. It takes whatever element type's constructor takes (in this case std::string). In the code above, a string is created after substring, and only then copied into result. Using iterator pair will eliminate the unnecessary copies.

Code

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <string_view>

std::vector<std::string> split_string(std::string_view content, std::string_view delimeter)
{
    std::vector<std::string> result;
    auto prev_pos = content.begin();
    auto next_pos = std::search(prev_pos, content.end(),
                               delimeter.begin(), delimeter.end());
    while (next_pos != content.end())
    {
        result.emplace_back(prev_pos, next_pos);
        prev_pos = next_pos + delimeter.size();
        next_pos = std::search(prev_pos, content.end(),
                               delimeter.begin(), delimeter.end());
    }

    if (prev_pos != content.end())
    {
        result.emplace_back(prev_pos, content.end());
    }
    return result;
}

int main()
{
    auto tokens = split_string("just a bunch of words", " ");

    std::copy(tokens.begin(), tokens.end(),
             std::ostream_iterator<std::string>{std::cout, ", "});
}

Demo.

Printing is done by copying the results into std::cout. Not everybody likes this, so just looping

for (const auto& token: tokens)

will do too.

Some readers might ask a question "Why not return std::vector<std::string_view>"? The answer is that the views might dangle if the conversion is done from temporary string. A good example would be

split_string(std::string{"string to split"}, "a");

The views would point to wherever the temporary is allocated, but after the function ends, the resulting views will dangle. One way to deal with this would be to create a function which copies, and name it split_string_copy, and let the current one to return views (hoping that IDE will put both version close, so developer would see the right one).

Yet another approach

Evangelists of iostream library might come up with a solution that modifies current locale, namely std::ctype<char>. Although it is really good at parsing simple CSV files, in a place where the function gets called multiple times it might be inefficient. Maybe in stateful cases it might prove as a better alternative.


Mapping interface between POJOs and DTOs

public interface Dto<K, V> extends Map<K, V> {} why don't you use simply a Map? Again, it is the same discussion related to marker interfaces we already had in your original question.

I'd define Mapper in the following way:

public interface Mapper<T, K, V> {
    public Dto<K, V> toDto(T obj);
    public T fromDto(Dto<K, V> dto);
}

I don't understand the reason why you need MapperImpl. What you need are concrete classes imlementing your interface for your specific types.

Imagine you want to map a Date to a Map<String,Integer>. You need something like this:

class DateMapper implements Mapper<Date, String, Integer>
{
    public Dto<String, Integer> toDto(Date date)
    {
        Dto<String, Integer> dto = new Dto<String, Integer>();
        dto.put("Day", date.Day());
        dto.put("Month", date.Month());
        dto.put("Year", date.Year());
    }

    public Date fromDto(Dto<String, Integer> dto)
    {
        return new Date(dto.get("Year"), dto.get("Month"), dto.get("Day"));
    }
}

I think that at this point you might be thinking at how you could obtain an instance of DateMapper. I think you should use some sort of factory or build it using reflection depending on what is better in your use case.


Nice question.... but, you're not doing a Radix Sort, but instead you're doing a Counting Sort

As it happens, a counting sort is probably the best sort algorithm you could choose for this problem, so there's no problem in the basic code, just the name you have given it.

There's a significant optimization you can do though, which will save a bunch of memory.... you don't need the aux array at all.

The "counting" part of your code is great:

int count[] = new int[radix];
for (int i = 0; i < data.length; i++) {
    count[data[i]]++;
}

but the actual sorting is a problem. This code:

int aux[] = new int[data.length];
int cumulate = 0;
for (int i = 0; i < radix; i++) {
    for (int j = 0; j < count[i]; j++)
        aux[cumulate + j] = i;
    cumulate = cumulate + count[i];
}
for (int i = 0; i < aux.length; i++) {
    data[i] = aux[i];
}

has a few problems. First up, the bad 1-liner for-statement:

    for (int j = 0; j < count[i]; j++)
        aux[cumulate + j] = i;

should be (with {} braces):

    for (int j = 0; j < count[i]; j++) {
        aux[cumulate + j] = i;
    }

and just manipulate the data array directly

int cumulate = 0;
for (int i = 0; i < radix; i++) {
    for (int j = 0; j < count[i]; j++) {
        data[cumulate + j] = i;
    }
    cumulate = cumulate + count[i];
}

I would actually restructure that loop to make it more apparent how the indexing is done... I would have:

int rad = 0;
for (i = 0; i < data.length; i++) {
    while (count[rad] == 0) {
        rad++;
    }
    count[rad]--;
    data[i] = rad;
}


Many languages (e.g. JavaScript, Perl) have a splice function of some sort to modify list contents. They allow you to insert list items or change existing ones to new sublists.

Python uses a "slice" approach, allowing you to specify many list edits without a specific splice function.

>>> myList = ["banana", "orange", "apple", "cherry", "grape"]
>>> myList[3:3] = ["mango", "papaya"]
>>> myList
['banana', 'orange', 'apple', 'mango', 'papaya', 'cherry', 'grape']

By the way, if this is hard to understand, this cheat sheet may help:

 ["banana", "orange", "apple", "cherry", "grape"]

  0_______  1_______  2______  3_______  4______ 5    # item index
  0:1_____  1:2_____  2:3____  3:4_____  4:5____      # equiv slice notation

  ^         ^         ^        ^         ^       ^    # slice notation for
  0:0       1:1       2:2      3:3       4:4     5:5  # 0_length positions
                                                      # between items

  0:2________________ 2:5_______________________      # misc longer slice
            1:4_________________________              # examples
            1:5_________________________________
            1:__________________________________
  0:____________________________________________
  :_____________________________________________
  :3__________________________
  :1______

There are also negative indices (counting from the end of the list). Let's not get into those right now!


Well if I'd review this I'd add the following:

The Id field in Product could be renamed id to follow java convention
Generally it's a good practice to have equals & hashcode methods overridden.

As for the database connection it depends on which Spring & database you are using, does it happen to be Spring Boot?


Find the maximum line length in a given TSV colum

This code can be recast into something that will be more efficient if all you are doing is scanning the file for the length of the longest line:

longest_item = None
for row in csv_reader:
    current_item_length = len(row[column])
    if current_item_length > longest_item:
        longest_item = current_item_length

Can be replaced with this:

longest_item = max((len(r[column]) for r in csv_reader))

So, what did we build here?  Working from the inside out:

len(r[column])

will return the length of the column in r. While

(len(r[column]) for r in csv_reader)

produces a generator which can return all of the lengths of column returned by csv_reader. And finally:

max((len(r[column]) for r in csv_reader))

returns the largest value of all of the column lengths.


Minor issues:

You need to include <utility> for std::forward.
You don't support empty tuples. It's obviously not a huge problem, but adding one line

template <> struct tuple<> {};

is no great burden either.
You should be using std::forward for the assignments in the make functions:

t.first = std::forward<T>(x);

so move assignment is used when x is an rvalue reference.

Slightly bigger issue:

Having no constructors in tuple means that your tuple can never contain a type that is not default constructible. "Default construction followed by assignment" is inherently less efficient than value construction. I would write perfect forwarding constructors for the tuple specializations, something like:

template <class T, class... Ts>
struct tuple<T, Ts...>
{
    T first;
    tuple<Ts...> rest;

    tuple() = default;
    template <class U, class...Us, class=
      typename ::std::enable_if<
        !::std::is_base_of<
          tuple,
          typename ::std::decay<U>::type
        >::value
      >::type
    >
    tuple(U&& u, Us&&...tail) :
      first(::std::forward<U>(u)),
      rest(::std::forward<Us>(tail)...) {}
};

template <class T>
struct tuple<T>
{
    T first;

    tuple() = default;
    template <class U, class=
      typename ::std::enable_if<
        !::std::is_base_of<
          tuple,
          typename ::std::decay<U>::type
        >::value
      >::type
    >
    tuple(U&& u) :
      first(::std::forward<U>(u)) {}
};

(All that enable_if junk is to keep the perfect forwarding constructors from being used for copy/move construction from another tuple.) This allows make_tuple to become a one-liner:

return tuple<typename ::std::decay<Ts>::type...>(::std::forward<Ts>(x)...);

(Code demo with suggested changes and the now-unnecessary builder templates removed)


I  reworked your code a little.  Here are the results from one test run.
Welcome to the guessing game! Guess one letter at a time. You have 5 incorrect guesses remaining.
The Secret Word Is: ------ (6)
Your Guess: a
The word does not contain the letter a.
You have 4 incorrect guesses remaining.
------
Your Guess: s
The word contains the letter s.
s-----
Your Guess: d
The word does not contain the letter d.
You have 3 incorrect guesses remaining.
s-----
Your Guess: f
The word does not contain the letter f.
You have 2 incorrect guesses remaining.
s-----
Your Guess: p
The word contains the letter p.
s---p-
Your Guess: g
The word does not contain the letter g.
You have 1 incorrect guesses remaining.
s---p-
Your Guess: h
The word does not contain the letter h.
You have 0 incorrect guesses remaining.
s---p-
Sorry, you didn't guess the secret word "sleepy".

Instead of counting tries up from zero, I counted down from 5.  If you decide to change the number of incorrect guesses, you only have to change it in one place.
I wrote a method to create a dashed word from the word for the secret word message.  I was hoping I could use the dashed word later, but I couldn't.
I still don't understand the character substitution for loop, but it works, so I left it alone.  Using a StringBuilder would greatly simplify your character substitution.
Here's the modified code.
import java.util.Scanner;

public class StringGuessingGame {

    public static void main(String[] args) {
        int incorrectGuesses = 5;
        boolean iterated = false;
        String temp = "";
        System.out.println("Welcome to the guessing game! Guess one letter "
                + "at a time. You have " + incorrectGuesses + " incorrect "
                        + "guesses remaining.");

        Scanner reader = new Scanner(System.in);

        String word = "sleepy";
        String dashedWord = createDashedWord(word);
        System.out.println("The Secret Word Is: " + dashedWord +
                " (" + word.length() + ")");

        do {
            System.out.print("Your Guess: ");
            String guess = reader.nextLine();
            boolean correctGuess = false;

            for (int i = 0; i < word.length(); i++) {
                if (guess.equals(Character.toString(word.charAt(i)))) {
                    correctGuess = true;
                    if (!iterated)
                        temp += Character.toString(word.charAt(i));
                    else {
                        String holder = Character.toString(
                                temp.charAt(i)).replace("-", guess);
                        temp = temp.substring(0, i) + holder +
                                temp.substring(i + 1, temp.length());
                    }
                } else {
                    if (!iterated) {
                        temp += "-";
                    }
                }
            }
            iterated = true;

            if (correctGuess) {
                System.out.println("The word contains the letter " + guess + ".");
            } else {
                System.out.println("The word does not contain the letter " + guess + ".");
                incorrectGuesses--;
                System.out.println("You have " + incorrectGuesses +
                        " incorrect guesses remaining.");
            }

            System.out.println(temp);
            if (temp.equals(word)) {
                System.out.println("You guessed correctly!");
                break;
            }

        } while (incorrectGuesses > 0);

        if (incorrectGuesses <= 0) {
            System.out.println("Sorry, you didn't guess the secret word \"" + word + "\".");
        }

        reader.close();

    }

    private static String createDashedWord(String word) {
        String output = "";
        for (int i = 0; i < word.length(); i++) {
            output += "-";
        }
        return output;
    }

}


Efficiently matching IP addresses with a list of CIDRs

First of all, welcome to Code Review! This is a great first question. There are some things to learn about how to post a question in order to get the best response, so I'll cover these first and then cover the performance problems that you're seeing.

Readability

You will get more reviews if your code is readable. I find the layout of your code very clear and readable apart from two things.

Your indenting uses only 2 spaces instead of the recommended 4.
Your variable names Dict and List are not descriptive and start with an uppercase letter (which is generally reserved for classes)

I understand that these two variables are not part of the code you use in the real world setting and were just quickly added for the purposes of this question. However, it's worth using clear variable names and standard indenting because the reviewer won't have your familiarity with the code.

Note that your List is not a list, since you have used braces { and } instead of square brackets [ and ]. Braces denote a set, or a dict if key value pairs are used. In your case List is a set, which has different behaviour.

Running your code before you post it

You didn't run this code before you posted it, and it contains syntax errors as pointed out by 200_success.
You can't be expected to spot every minor typo in your code before you post it. However, you are expected to run the code before you post it. This would have picked up the problem with Dict and with List. It only takes a moment and means you will get more meaningful reviews, less confusion, and use up less of the reviewers time so they can help more people.

Since the site rules require working code, it would be perfectly reasonable for a reviewer to simply move on to the next question if this one has code that doesn't run. For this reason you are also likely to get more reviews and to see your first review sooner if you run your code before posting it.

For reference, the syntax errors on both lines are due to not enclosing strings in quotes, so that python tries to evaluate them as expressions.

Dict = {127.0.0.0/8 : ABC, 169.128.0.0/16 : DEF}
List = {127.0.0.1, 126.1.1.1, 169.2.2.2, 150.0.22.2}

should be:

Dict = {'127.0.0.0/8' : 'ABC', '169.128.0.0/16' : 'DEF'}
List = {'127.0.0.1', '126.1.1.1', '169.2.2.2', '150.0.22.2'}

Repeating work

You are repeating two things, each of which slows down your program.

You convert IP using ipaddress.ip_address(IP). This conversion always gives the same output for a given IP, so you can calculate it once at the start of the outer loop rather than recalculating the same thing every time you start the inner loop.
You convert CIDR using ipaddress.ip_network(CIDR). Each time through the inner loop you will be converting the same list of CIDRs. If you have sufficient memory you can calculate all of these once, and then use those precalculated values rather than recalculating.

You state that there are 10,000 CIDRs and 5,000 IPs.

The first problem will therefore repeat the IP conversion on average 5,000 times for cases where a match is found (because on average it will get half way through the 10,000 CIDRs before finding the match). Where no match is found it will repeat the IP conversion 10,000 times, once for each CIDR. Between 5,000 and 10,000 conversions for each of 5,000 IPs is between 25,000,000 and 50,000,000 conversions when only 5,000 are needed (once per IP).

The second problem will repeat all 10,000 CIDR conversions for any IP that does not find a match, and on average 5,000 CIDR conversions for any IP that does find a match. That's between 25,000,000 and 50,000,000 conversions when only 10,000 are needed (once per CIDR).

How to return an unconverted CIDR

I can see why you might be tempted to loop over unconverted CIDRs - you return an unconverted CIDR so working with a list of converted CIDRs would mean you'd have to find out which CIDR the converted CIDR came from before returning it.

You can return the unconverted CIDR by creating a dict at the start which has converted CIDR as the key and original CIDR as the value.

For example:

converted_CIDRs = {ipaddress.ip_network(CIDR):CIDR for CIDR in Dict.keys()}

Now you can work with converted CIDRs to avoid all that recalculation, and still return an unconverted CIDR at the end by doing a quick dictionary lookup using the converted CIDR as the key.


Program to print a Python list as "a, b, and c"

# defining possible lists

Don't write comments that describe what the code does; we can see the code, we know what it's doing. If you ever need comments, it's where it's otherwise unclear why the code's doing it.

lists = ['cars','favorite foods','family members']

Per the style guide, you should put spaces after the commas:

lists = ['cars', 'favorite foods', 'family members']

x = ['Hyundai','Acura','Honda','Suzuki','Ford']

x is a terrible name for this list (see also: y, z). Names should be more descriptive:

cars = ['Hyundai', 'Acura', 'Honda', 'Suzuki', 'Ford']

But given that lists is supposed to refer to the three lists below it, why not use a dictionary instead:

lists = {
    'cars': ['Hyundai', 'Acura', 'Honda', 'Suzuki', 'Ford'],
    ...
}

def listselection():
    print('The following lists exist within the system. Which would you like to see?')
    print(lists)

The style guide recommends snake_case names for functions. It's helpful to include a docstring when you define a function. Given the above switch to a dictionary, we need to change the second line slightly:

def list_selection():
    """Show the user the selection of available lists."""
    print('The following lists exist within the system. Which would you like to see?')
    print(list(lists))

Note that by default you get a dictionary's keys when you iterate over it, so list(lists) == ['cars', ...].

def errorchecking():
    global option

    while True:
        try:
            option = str(input())
        except:
            print('Please type letters, not numbers.')
            continue

        if option == 'cars':
            break
        elif option == 'favorite foods':
            break
        elif option == 'family members':
            break
        else:
            print('Please re-enter your selection')

    return option

Using a while True loop to take and validate input is a good idea, but there are a few problems here:

Why do you use global option? You return option at the end of the function, which is the way you ought to provide it to other functions. Using global state is a bad pattern, get out of the habit of doing it.
Your error checking doesn't actually do anything. The result of input(...) is always a string, str(input(...)) will never cause an exception. Also your error checking is too broad; bare except is a bad idea, you should be specific about the kind of errors you expect and allow unexpected exceptions to get raised up. "Errors should never pass silently. Unless explicitly silenced."
This part:

if option == 'cars':
    break
elif option == 'favorite foods':
    break
elif option == 'family members':
    break
else:
    print('Please re-enter your selection')

is not very DRY (Don't Repeat Yourself); we already have those options, they're the keys to our dictionary (or the values of your list in the original). Therefore we could write:

if option in lists:
    break
else:
    print('Please re-enter your selection')

With all of the above changes the function is now a lot more concise:

def error_checking():
    """Take valid input from the user."""
    while True:
        option = str(input())
        if option in lists:
            return option  # this will also end the loop
        print('Please re-enter your selection')

Now it's clear that error_checking doesn't really describe what this function does; that's only part of its job, but the name should tell you how to use it. I would call it something like get_valid_input.

def listconcatenation():
    global spam
    global listitem

    listitem = 'Here are the items in my list: '

    if option == 'cars':
        spam = x
    elif option == 'favorite foods':
        spam = y
    elif option == 'family members':
        spam = z

    for i in spam:
        if spam.index(i) < (len(spam)-1):
            listitem = listitem + i + ', '
        else:
            listitem = listitem + 'and ' + i + '.'

    return listitem

Same things again: put underscores in the names; remove the global state (make option a parameter instead, you already return listitem). But there are three more specific improvements:

The dictionary we introduced above means you can go from this:

if option == 'cars':
    spam = x
elif option == 'favorite foods':
    spam = y
elif option == 'family members':
    spam = z

to this:

item_list = lists[option]  # note also a more descriptive name

That said, why do this inside list_concatenation? That makes that function very tightly coupled to the place where you're currently using it, it's not reusable at all. Instead, why not pass in the selected list, rather than the option name, as a parameter?

Similarly including things like 'Here are the items in my list: ' and the trailing full stop '.' within the function reduce its reusability.
In terms of looping in Python:

for i in item_list:
    if item_list.index(i) < (len(item_list)-1):
        listitem = listitem + i + ', '
    else:
        listitem = listitem + 'and ' + i + '.'

The i would usually suggest an index, perhaps item would be a better name. If you want the index, rather than using spam.index(item) you can enumerate over the list:

for index, item in enumerate(item_list):
    if index < (len(item_list) - 1):

This is more efficient as you're only passing over the list once, rather than every time you need the index. Note the additional whitespace, again per the style guide.

With all of the above, we have to change the invocation of the functions:

list_selection()
item_list = lists[take_valid_input()]
result = list_concatenation(item_list)
print('Here are the items in my list: {}.'.format(result))

Now the data is moving through the functions in a logical way, rather than being updates to the global module state, and list_concatenation is a very generic, reusable function.

I might also be inclined to move list_selection inside take_valid_input, or even write a more generic function for user input that:

Takes a dictionary of options;
Displays the option names to the user;
Loops until they've entered one of the option names; and
Returns the one they've entered.