Sort string's characters into alphabetic order

Don't use using namespace std

You don't need a stringstream or an istringstream or a vector for this. std::sort can be performed on a string directly. An std::string_view can be used to avoid copying (more on this later)

There seems to be 3 options how to make this work best. If you don't care about chewing up your original string you can perform the operations on it directly without ever copying anything. Here you will pass by reference:

std::string& AlphabetSoup(std::string& str) {
   std::sort(str.begin(), str.end());
   str.erase(std::remove(str.begin(), str.end(), ' '), str.end());

 return str; // or omit this and change the return value to void
}

You can also pass by value which will copy your string and leave the original intact:

std::string AlphabetSoup(std::string str) {
   std::sort(str.begin(), str.end());
   str.erase(std::remove(str.begin(), str.end(), ' '), str.end());

 return str;
}

Or you can pass in as a std::string_view which will not copy.

std::string AlphabetSoup(std::string_view str) {
   std::string s(str);
   std::sort(s.begin(), s.end());
   s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
   return s;
}

The method I used to remove the spaces is known as the erase-remove idiom. The character specified in the remove() function is moved to the end of the range (provided as parameters) where they can be efficiently erased. There are faster iterators on sorted sets that can speed things up as @TobySpeight pointed out but I haven't used them. (Namely std::lower_bound and std::upper_bound)

Consider providing test cases and output. This too will help reviewers and make it more likely for you to get solid answers.


Create an object based on data from a text file

I see that the processing you're doing here does not depend on the order you're processing in. This means you can parallelize the processing heavily.

Additionally you're doing line-by-line processing, which allows you to use one of the new features of Java 8, namely Files.lines

This greatly simplifies the code you have to following outline:

try (Stream<String> lines = Files.lines(path).parallel()) {
   // do line by line processing
} catch (IOException e) {
   // sensible handling
}

Also it might be faster to keep parsables in "one" file, this reduces channel and OS waiting overhead for Open/Close operations when doing I/O


The code looks good and works well. Since it provides a useful bit of work, you should convert it into a function. Then you can copy that function to another program if you need so.

function yyyymmdd() {
    var x = new Date();
    var y = x.getFullYear().toString();
    var m = (x.getMonth() + 1).toString();
    var d = x.getDate().toString();
    (d.length == 1) && (d = '0' + d);
    (m.length == 1) && (m = '0' + m);
    var yyyymmdd = y + m + d;
    return yyyymmdd;
}

To make this code a little easier to read, you should rename x to now.

You could also omit the calls to toString(), which makes the code a little shorter. Plus, you should introduce the variables mm and dd, so that you don't reassign to the d and m variables. This is a generally useful pattern, because when stepping through the code you can always look at the variable definition to see how it was computed. This is not possible for variables that change their value during execution.

The modified code looks like this:

function yyyymmdd() {
    var now = new Date();
    var y = now.getFullYear();
    var m = now.getMonth() + 1;
    var d = now.getDate();
    var mm = m < 10 ? '0' + m : m;
    var dd = d < 10 ? '0' + d : d;
    return '' + y + mm + dd;
}

Or, you could inline the last few lines:

function yyyymmdd() {
    var now = new Date();
    var y = now.getFullYear();
    var m = now.getMonth() + 1;
    var d = now.getDate();
    return '' + y + (m < 10 ? '0' : '') + m + (d < 10 ? '0' : '') + d;
}

That last variant is harder to read though, therefore I prefer the previous one.

Another possibility is to define a helper function that produces a two-digit string:

function yyyymmdd() {
    function twoDigit(n) { return (n < 10 ? '0' : '') + n; }

    var now = new Date();
    return '' + now.getFullYear() + twoDigit(now.getMonth() + 1) + twoDigit(now.getDate());
}


As I can't comment, the philonus's answer is the clearer and best for me, if you want to display zero you can do this, initializing the stats array:

$input = array(
    "report=D","report=D","report=D","report=I","report=I"
);

$stats = array(
    'U' => 0,
    'D' => 0,
    'I' => 0,
);
foreach($input as $value) {
    $types = explode('=', $value);
    $stats[$types[1]]++;
}

print_r($stats);


Check for correct number of elements in exploded string

There are several options.

My favorite (based on readablity and simplicity) is using array_filter to remove everything that is not a number from the array and then comparing with the original to see if anything changed, then using count to make sure you have the correct number of elements:

$str = '1-foo-3';
$strSplit = explode('-', $str);

if(count($strSplit) == 3 && $strSplit == array_filter($strSplit, 'is_numeric')){
    // array is numeric // run code
} else {
    // array is non-numeric
}

Edit: did some speed testing and tried a few more options and validations.

I speedtested with the following inputs:

A: $strSplit = explode('-', '1-2-3');//3 elements, all numeric //evaluates true
B: $strSplit = explode('-', '1-foo-3-4');//4 elements, not all numeric //evaluates false

The results (after 1 million cycles) were as follows :

Static isset and is_numeric :

if (isset($strSplit[0]) && is_numeric($strSplit[0]) && isset($strSplit[1]) && is_numeric($strSplit[1]) && isset($strSplit[2]) && is_numeric($strSplit[2]) && !isset($strSplit[3])) {
    // some code
    // A : speed 0.68 mircoseconds
    // B : speed 0.48 mircoseconds
}

Looped isset and is_numeric :

for($i=0; $i<3;$i++) if(!isset($strSplit[$i]) || !is_numeric($strSplit[$i])) $nonNumeric = true;

if(!isset($strSplit[($i+1)]) && !isset($nonNumeric)){
    // some code
    // A : speed 0.96 mircoseconds
    // B : speed 1.00 mircoseconds
}

count and array_filter :

if(count($strSplit) == 3 && $strSplit == array_filter($strSplit, 'is_numeric')){
    // some code
    // A : speed 2.00 mircoseconds
    // B : speed 0.16 mircoseconds
}


First, I'll mark a couple of things:

Parsing variables to strings.

You should just choose a form to parse variables into strings and stick with it.

print("Here is the hidden word:", ' '.join(hidden_word))
print("You have %d tries" % chances_left)

You're using .join and %d, %s to print variables. I suggest you to just use format (like I've done in the sample code), because you don't have to worry about parsing data. It allows you to be cleaner and has powerful options. Plus, % formatting is deprecated as far as I know.

The .join function is useful when you're using it to create a new string from a couple of different strings. Else, use format.

Classes and objects.

In your code, you're using a class with "only" a constructor.

The method show_word is kind of useless in Python, because you can access it directly, no need for a method to receive the element.
The method hide_word is used only one time. It should be called from the constructor and use it to create hidden_word.

The main.py code is just functional programming. You should use methods to make it cleaner and easier to read. Plus, you're just using your class to pass the elements from it to the while loop in the main, instead of using it as a class.

My final suggestion is that you look for Object Oriented Programming tutorials and examples, since you're using it very poorly and badly. Don't worry, you'll improve over time :)
Take a look to PEP8 style guide for Python too, it will help you to write cleaner and more readable.

I leave you this code as a suggestion, try to look for everything you don't understand.

import linecache
import random

class HiddenWord():

    def __init__(self, word):
        """Gets a word and turns it into a list. Then hides it as another list in hidden_word"""
        self.word = list(word.upper())
        self.hidden_word = []
        for letter in self.word:
            if letter == " ":
                self.hidden_word.append(" ")
            else:
                self.hidden_word.append('*')

    def check_letter(self, letter):
        """Checks if the letter received is in the word. If it is,
           it will make it visible in the hidden word, and will return true.
           If it isn't, it will just return false."""
        letter = letter.capitalize()
        if letter in self.word:
            for index in range(len(self.hidden_word)):
                if(self.word[index] == letter):
                    self.hidden_word[index] = letter

            return True

        return False

class Game():
    def number_lines(self):
        """Gets the number of lines that the txt has"""
        num_lines = sum(1 for line in open('Words.txt'))
        return num_lines

    def printInfo(self):
        """Shows by console tries left, the hidden word and the used letters"""
        print("Tries left: {}".format(self.chances_left))
        print("Hidden word: {}".format(self.hw.hidden_word))
        print("Used letters: {}".format(self.used_letters))

    def __init__(self):
        """Gets a word from the .txt and initialises the hidenword class"""
        word = linecache.getline("Words.txt", random.randint(1, self.number_lines()))[:-1]
        self.hw = HiddenWord(word)
        self.chances_left = int(len(self.hw.word) / 2 + 1)
        self.used_letters = []
        self.misses = 0

    def gameFinish(self):
        """Check if the player has won"""
        if (self.hw.hidden_word == self.hw.word):
            return True

        return False

    def play(self):
        """Main game"""
        while(self.chances_left > 0 and not self.gameFinish()):
            self.printInfo()
            letter = ""
            while(not letter or letter in self.used_letters):
                letter = input("Choose a letter: ")

            self.used_letters.append(letter)

            if(self.hw.check_letter(letter)):
                print("Bingo! That letter is in the word.")
            else:
                print("That letter is not in the word.")
                self.misses += 1
                self.chances_left -= 1

            if(self.gameFinish()):
                if(self.misses == 0):
                    print("Congratulations! You did it without missing a single time!")
                else:
                    print("Congratulations! You did it! But you've missed {} time(s)".format(self.misses))
                break

        print("You lost. The word was {}.".format(self.hw.word))

if __name__ == '__main__':
    """Main loop"""
    try_again = 'y'
    while try_again == 'y':
        game = Game()
        game.play()

        try_again = input("Would you like to try again ? (y/n)").lower()

        while not try_again.lower() in ('y', 'n'):
            try_again = input("Please provide a valid answer: ")

    print("See you!")


Class that handles header and footer includes looks like a mess

Separation of Concerns

You should implement Separation of Concerns. In your case, don't mix logic with your view. Follow basic MVC, where M (model) is the data source, V (view) is where your HTML is, and C (controller), where all your logic is. In this case, put your HTML in one file, the logic in the other.

Templating

One thing that messes up development is when logic is mixed to the template. It makes the template messy and hard to maintain and visualize. I suggest you take a look at the PHP implementation of Mustache templates. In your controller, simply make a function that loads the template to a variable, feeds it to Mustache, put some data in and done.

Inheritance

One use of inheritance is to hide utility functions. For instance, you can create a View class, where your future views inherit from.

End Result

You can simply do something as simple as this in the controller!

public function index(){
    $myView = new View('path/to/template');     // Create a view
    $myDataSource = new Model('MODEL_NAME');    // Create a model
    $theData = myDataSource->getData();         // Grab data
    $theResultHTML = myView->render($theData);  // Render data to template and print
}


Finding the closest pair of numbers which add to a target number

Human Computer Interaction

Prompts

        li = input("enter the first sequence of numbers by giving exactly one space between numbers:")
        lj = input("enter the second sequence of numbers by giving exactly one space between numbers:")

These are awfully long prompts for the user to enter in a list of values after.  Maybe instructions, and then two short input prompts?

        print("Enter two space separated integer number sequences, of the same length.")
        li = input("First sequence:  ")
        lj = input("Second sequence: ")

White-space separators

li.split(" ") will separate a string into a number of items separated by exactly one space.  If the user wants to enter a single digit number on one line, and a two digit number on the next, and keep the columns of numbers lined up, they can't use extra spaces.

.split(), with no arguments, will split a string into a number of items separated by one or more white-space characters.

>>> "     2     3 \t   \n  4 \r  5     ".split()
['2', '3', '4', '5']

No hard requirements to use exactly one space.  And leading and trailing spaces are trimmed, too!

Unexpected Behaviour

def pair_finder(list1, list2, t):
    list1.sort()
    list2.sort()
    ...

After calling pair_finder(l1, l2, target), you'll find that l1 and l2 have been sorted!  The caller probably did not expect that.

Use:

def pair_finder(list1, list2, t):
    list1 = sorted(list1)
    list2 = sorted(list2)
    ...

The sorted(...) function doesn't modify the input list, and it returns a new list.  By assigning those to the original variables, list1 & list2 will be sorted, but the caller's l1 & l2 lists won't be touched.

Pythonic Constructs

Loop like a native

List comprehension

l1 = []
for i in li.split(" "):
    l1.append(int(i))

This is an inefficient construct.  You are creating a list, and then expanding the list one item at a time.

You could create the list all at once, using list comprehension:

l1 = [int(i) for i in li.split(" ")]

And applying the same operation to every item in a sequence is called a mapping operation, and Python has a built-in map(func, sequence) function:

l1 = list(map(int, li.split(" ")))

Or, combining with the input and using the better space handling:

print("Enter two space separated integer number sequences, of the same length.")
l1 = list(map(int, input("First sequence:  ").split()))
l2 = list(map(int, input("Second sequence: ").split()))

Enumerate

        k = 0
        for j in list2:
            ...
            k += 1

This should be replaced with:

        for k, j in enumerate(list2):
            ...

to allow Python to maintain the k index while walking through the list2 items.

Extending Lists

Adding a list to another list is a list.extend(...) operation:

pairs = []
for q in pairs_low:
    pairs.append(q)
for w in pairs_high:
    pairs.append(w)
for r in pairs_equal:
    pairs.append(r)

Could become simply:

pairs = []
pairs.extend(pairs_low)
pairs.extend(pairs_high)
pairs.extend(pairs_equal)

if ... elif

        if i + j < t:
            ...
        if i + j > t:
            ...
        if i + j == t:
            ...

If the sum is less than t, it won't be greater than t, or equal to t.  And if it is greater than t, it won't be equal to t.  And if it is not less than or greater than t, it can only be equal to t.  Why do the extra comparisons?

        if i + j < t:
            ...
        elif i + j > t:
            ...
        else:
            ...

PEP-8

Unnecessary parenthesis:

            elif (i + j == t_low):

Variable names too short to be meaningful

li, lj, l1, l1, q, w, r, t

Main guard

Mainline code should be protected with

if __name__ == '__main__':
    ...

to allow the file to be imported into another file, for unit tests, etc.

Algorithmic Improvements

pair_finder() starts off by sorting both input lists.  That is an \$O(N \log N)\$ operation.  Then it reverses one of the lists, which is an \$O(N)\$ operation.  And then ...

for i in list1:
    ...
    for j in list2:
        ...

... which is \$O(N^2)\$!  Right now, this is the time consuming part of the algorithm.  But what are we doing?  We are looking for two numbers which sum to target.  Let’s turn that around:

for i in list1:
    desired = target - i
    # find “desired” in list2

Well, list2 is sorted, so we can do a binary search to find the desired value.

for i in list1:
    desired = target - i
    pos = bisect.bisect_left(list2, desired)
    ...

The binary search is \$O(\log N)\$, so with the outer loop, the time complexity has dropped to \$O(N \log N)\$, the same as the sorting.

The desired value may or may not be in list2.  If it is, it is at list2[pos].  Assuming we don’t fall off the start of list2, then for the current i value, i+list2[pos-1] would be the largest sum less than target.

Assuming we don’t fall off the end of list2, if list2[pos] == desired, then the sum i+list2[pos+1] will be the smallest sum greater than target for the current value of i.

for i in list1:
    desired = target - i
    pos = bisect.bisect_left(list2, desired)
    if pos < len(list2):
        if list2[pos] == desired:
            # add (i, desired) to pairs_equal
            low, high = pos - 1, pos + 1
        else:
            low, high = pos - 1, pos
        if low >= 0:
            # add (i, list2[low]) to pairs_low, if >= t_low
        if high < len(list2):
            # add (i, list2[high]) to pairs_high, if <= t_high

But ... what about duplicates?  If list2 contains duplicate values, pos + 1 may not be sufficient to advanced to a value larger than desired.  You could use both bisect_left and bisect_right to find either end of a sequence of multiple desired values.  The difference in right and left would be the count of those values, and you could add [(i, desired)] * count to pairs_equal.  But you’d also need to do the same for the pairs_low and pairs_high, which means more binary searching to find those ends.  Or, you could use two collections.Counter objects to count occurrences of each value in list1 and list2, and then remove duplicates values from list1 and list2.  Any pairs added would need to be replicated by the product of the respective counts to occur the correct number of times in the result.


Create an array which contains specific values of a specific nested object inside an array

You could use _.reduce() (or alternatively native Array.reduce()) to achieve this:

const workflow = _.reduce(
    template_columns,
    (colResult, colValue) => {
        return colResult.concat(
            _.reduce(
                colValue.workflow,
                (workflowResult, workflowValue) => workflowValue.action,
                []
            );
        );
    },
    []
);

or

const workflow = template_columns.reduce(
    (colResult, colValue) => {
        return colResult.concat(
            colValue.workflow.reduce(
                (workflowResult, workflowValue) => workflowValue.action,
                []
            );
        );
    },
    []
);

Note, use of arrow functions is optional, but since you indicated you are writing for ES6 and transpiling, and since the callback logic is so simple here, I thought the arrow function made sense.

Alternately, you might perform reduce then map like this:

const workflow = _.map(
    _.reduce(
        template_columns,
        (result, value) => result.concat(value.workflow),
        []
    ),
    val => val.action
 );

This approach is actually similar to your current approach, using _reduce() rather than combination of _.flatten and _.map inside the outer _map() call.

Perhaps try it both ways (as well as your original approach) and see where you get best performance, based on the typical data you are working with.


Button to dynamically clone a form field

Combining the answers and work with the limitations of django the html now looks like this:

<form id="create" method="post" action="/create/">
  <input name="choice_set-TOTAL_FORMS" type="hidden" value="5" />
  <input name="choice_set-INITIAL_FORMS" type="hidden" value="0" />
  <input name="choice_set-MIN_NUM_FORMS" type="hidden" value="1" />
  <input name="choice_set-MAX_NUM_FORMS" type="hidden" value="20" />

      Choice:
        <input maxlength="200" name="choice_set-0-choice_text" type="text" />

      Choice:
        <input maxlength="200" name="choice_set-1-choice_text" type="text" />

      Choice:
        <input maxlength="200" name="choice_set-2-choice_text" type="text" />

      Choice:
        <input maxlength="200" name="choice_set-3-choice_text" type="text" />

      Choice:
        <input maxlength="200" name="choice_set-4-choice_text" type="text" />

    <button type="button" id="add-choice">Add another choice
    </button>

  <input type="submit" value="Create" />
</form>

And the script like this:

function $(selector, element) {
    if (!element) {
        element = document
    }
    return element.querySelector(selector)
}

function $$(selector, element) {
    if (!element) {
        element = document
    }
    return element.querySelectorAll(selector)
}

function hasReachedMaxNum(type, form) {
    var total = parseInt(form.elements[type + "-TOTAL_FORMS"].value);
    var max = parseInt(form.elements[type + "-MAX_NUM_FORMS"].value);
    return total >= max
}

function cloneMore(element, type, form) {
    var totalElement = form.elements[type + "-TOTAL_FORMS"];
    total = parseInt(totalElement.value);
    newElement = element.cloneNode(true);
    for (var input of $$("input", newElement)) {
        input.name = input.name.replace("-" + (total - 1) + "-", "-" + total + "-");
        input.value = null
    }
    total++;
    element.parentNode.insertBefore(newElement, element.nextSibling);
    totalElement.value = total;
    return newElement
}
var addChoiceButton = $("#add-choice");
addChoiceButton.onclick = function() {
    var choices = $("#choices");
    var createForm = $("#create");
    cloneMore(choices.lastElementChild, "choice_set", createForm);
    if (hasReachedMaxNum("choice_set", createForm)) {
        this.disabled = true
    }
};


Doing an ROP style bind for two functions on the same input in a pipeline

I actually wouldn't bother defining a bind2 as this can lead to an explosion, bind3, 4, 5, 6. Instead I would define a simple computation builder to do this. So using your code from above.

 type DemoBuilder() =
     member x.Bind(m,f) = bind f m
     member x.Return(s) = Success s

 let demo = DemoBuilder()

which you can then use like so

 let DemoB x =
    demo {
        let! input = x
        let! a = demo1 input
        let! b = demo2 a
        let! c = demo3 a
        return (b,c)
    }

 DemoB (Success 1)


A Pythonic implementation of Conway's Game of Life

Your code is pretty good, and there's not much I'd change. However I would change it in the following ways:

It's standard to use UPPER_SNAKE_CASE for Enum values.
It's preferred to use typing.Sequence over typing.List to annotate arguments.
When you have to comment what a variable is, it indicates you've chosen a bad name. Instead use rows over m.
Either put your comprehensions on one line or split them out.

# Current way
[
    [State(init[i][j]) for j in range(self.n)] for i in range(self.m)
]

# One line
[[State(init[i][j]) for j in range(self.n)] for i in range(self.m)]

# Multiple lines
[
    [
      State(init[i][j])
      for j in range(self.n)
    ]
    for i in range(self.m)
]

It's easier to read a comprehension in a function if you keep the brackets together.

# Current
return '\n'.join([
    ''.join(
            ['*' if cell.value else ' ' for cell in row]
    ) for row in self.board_]
)

# Together
return '\n'.join([
    ''.join(['*' if cell.value else ' '
             for cell in row])
        for row in self.board_])

# Together and multiple lines
return '\n'.join([
    ''.join([
        '*' if cell.value else ' '
        for cell in row
    ])
    for row in self.board_
])

You don't need to use the surrounding brackets if your comprehension is the only argument to a function. However, this may be a couple of u seconds slower, which shouldn't matter to most people.

return '\n'.join(
    ''.join(
        '*' if cell.value else ' '
        for cell in row
    )
    for row in self.board_
)

I'd make another function neighbours. I find this nicer, as finding the neighbors can be a little annoying, and take away from the actual algorithm.

I'd also make the algorithm use a premade list, that filters out x==i already.

NEIGHBOURS = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i or j]

def neighbours(self, x: int, y: int) -> Iterator[Tuple[State, int, int]]:
    for i, j in ((x+i, y+j) for i, j in NEIGHBOURS):
        try:
            yield self.board_[i][j], i, j
        except IndexError:
            pass

def count_live_neighbours(self, x : int, y : int) -> int:
    ''' count the live neighbours of a cell '''
    return sum(cell.value for cell, _, _ in self.neighbours(x, y))

Your next_cell_state function can be simplified.

Your two ifs return State.ALIVE.
They can be merged together.
You can return early if count is three.
You can simplify the rest of the checks.

def next_cell_state(self, x : int, y : int) -> State:
    count = self.count_live_neighbours(x, y)
    if count == 3 or (count == 2 and self.board_[x][y] == State.ALIVE):
        return State.ALIVE
    return State.DEAD

import numpy as np
import time

from enum import Enum
from typing import List, Iterator, Sequence, Tuple

NEIGHBOURS = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i or j]

class State(Enum):
    ''' enum class to represent possible cell states '''
    DEAD = 0
    ALIVE = 1

class Board:
    ''' Board class to represent the game board '''
    def __init__(self, rows : int, columns : int, init : Sequence[Sequence[int]]):
        self.rows = rows   # the number of rows
        self.columns = columns   # the number of columns
        self.board_ = [
            [
                State(init[i][j])
                for j in range(self.columns)
            ]
            for i in range(self.rows)
        ]

    def __str__(self) -> str:
        ''' return the __str__ representation of a Board object
            * represents a live cell, and a space represents a dead one
        '''
        return '\n'.join([
            ''.join([
                '*' if cell.value else ' '
                for cell in row
            ])
            for row in self.board_
        ])

    @property
    def population(self) -> int:
        ''' population — the number of live cells on the board '''
        return sum(cell.value for row in self.board_ for cell in row)

    def has_live_cells(self) -> bool:
        ''' return whether there are any live cells or not '''
        return any(cell.value for row in self.board_ for cell in row)

    def neighbours(self, x: int, y: int) -> Iterator[Tuple[State, int, int]]:
        for i, j in ((x+i, y+j) for i, j in NEIGHBOURS):
            try:
                yield self.board_[i, j], i, j
            except IndexError:
                pass

    def count_live_neighbours(self, x : int, y : int) -> int:
        ''' count the live neighbours of a cell '''
        return sum(cell.value for cell, _, _ in self.neighbours(x, y))

    def next_cell_state(self, x : int, y : int) -> State:
        count = self.count_live_neighbours(x, y)
        if count == 3 or (count == 2 and self.board_[x][y] == State.ALIVE):
            return State.ALIVE
        return State.DEAD

    def next_board_state(self) -> List[List[State]]:
        ''' return board configuration for the next state '''
        return [
            [
                self.next_cell_state(i, j)
                for j in range(self.columns)
            ]
            for i in range(self.rows)
        ]

    def advance_state(self):
        ''' update the board configuration with the config for the next state '''
        self.board_ = self.next_board_state()

if __name__ == '__main__':
    arr = np.random.choice([0, 1], (20, 100), p=[0.90, 0.1])
    board = Board(arr.shape[0], arr.shape[1], init=arr.tolist())

    step = 0
    while board.has_live_cells():
        step += 1
        print(board)
        print('f{step} {board.population}')
        board.advance_state()

        time.sleep(.1)


Naming Convention

It is common practice and part of the SUN / Oracle Code Conventions for the Java Programming Language to start variable names with lowercase.
Thus, you might want to rename ChartData to chartData.

Oh, and j is not an acceptable name for an Iterator.
A few lines down, I can no longer remember what j was.
Usually, j is an int and used because i was used already.
And in fact you already do have an int i.

In such a case, name the Iterator it or iter or even iterator but not j.

Also, the name me for Map.Entry is a bit confusing, because the abbreviation me is a valid English word at the same time.
I'd rename me to entry.

Iterating over Map entries

Your code for iterating over the map entries is too complex.

Here's the relevant part of your code:

HashMap hm = (HashMap) value; // context
Set set = hm.entrySet();
Iterator j = set.iterator();
while (j.hasNext()) {
    Map.Entry me = (Map.Entry) j.next();
    // Do something with me.
}

You can remove the cast by telling the Set and the Iterator that they are from a Map, which means they are a Set<Map.Entry> and an Iterator<Map.Entry>.
This simplifies the code as follows:

HashMap hm = (HashMap) value; // context
Set<Map.Entry> set = hm.entrySet();
Iterator<Map.Entry> j = set.iterator();
while (j.hasNext()) {
    Map.Entry me = j.next();
    // Do something with me.
}

You can further simplify this by turning this into a for-each loop:

HashMap hm = (HashMap) value; // context
for (Map.Entry me : hm.entrySet()) {
    // Do something with me.
}

Abstract datatypes

Whether your map is a HashMap or something else is probably irrelevant.
Therefore you might want to change the datatype of variable hm from HashMap to Map.

Map hm = (Map) value;

How to check types

Java has an instanceof operator.

Your type check compares the toString() result of the class.
That has a few issues.

Your comparison relies on a specific format of Class.toString() which is not guaranteed. If you must compare the name, use getName() instead of toString().
Your comparison is case-insensitive, which is definitely the wrong thing to do in a case-sensitive language. java.util.HashMap and java.util.hashmap could in theory both exist but would be separate classes. Your code would treat java.util.hashmap as if it were the same as java.util.HashMap, which is wrong.
Your comparison checks on the class, ruling out possible subclasses of HashMap as well as alternative Map implementations. In a broader sense, you're violating the LSP - Liskov Substitution Principle.

You might want to go for this code to check the type:

Object value = field.get(currObj);
if (value instanceof HashMap) // ...

or even

Object value = field.get(currObj);
if (value instanceof Map) // ...

Interlude: New source code as of now

for (Object currObj : chartData) {
    for (Field field : currObj.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        Object value = field.get(currObj);
        if (value instanceof Map) {
            Map hm = (Map) value;
            for (Map.Entry entry : hm.entrySet()) {
                if ((entry.getKey().toString().equalsIgnoreCase("y"))) {
                    assertTrue(Long.parseLong(me.getValue().toString()) == anArrayOfObjects[i][0]); // check pairs
                    System.out.println("Actual y value - " + me.getValue().toString() + " expected value - " + anArrayOfObjects[k][0].toString());
                    i++;
                }

                if ((entry.getKey().toString().equalsIgnoreCase("x"))) {
                    assertTrue(Long.parseLong(me.getValue().toString()) == anArrayOfObjects[k][1]);// check pairs
                    System.out.println("Actual x value - " + me.getValue().toString() + " expected value - " + anArrayOfObjects[k][1].toString());
                    k++;
                }
            }
        }
    }
}

Method length

This method is far too long to be even close to maintainable source code.
As software craftsmen, we say that regarding method length Java code is maintainable if (almost) all of its methods have 5 or fewer lines.
10 lines is something which I already do not accept in production code.
(Exceptions like some GUI creation code apply.)

The code should be split into several methods.
I know that you might even have tried this - and failed, due to the local variables i and k.

Let's remember what Uncle Bob said: "Long functions are where classes use to hide." and "Extract 'till you drop" (Robert C. Martin, "Clean Code")

Refactorings to apply to get smaller methods

Extract method object.
Turn local variables i and k into fields and introduce getters for them (you wouldn't increment them if you wouldn't need them later).
Refactor the constructor argument into an argument to invoke().
Rename invoke to visit.
Extract every multiline block into a separate method with a meaningful name.
Make the two branches for "x" and "y" look identical by replacing everything which is different with variables. For that piece of code which is different we use two methods implementing a functional interface Incrementor so we can store a method reference in a variable.

Here's how this looks like as a class:

private static class ChartDataVisitor {
    private int i = 0;
    private int k = 0;

    public void visit(Iterable<Object> chartData) throws IllegalAccessException {
        reset();
        visitChartData(chartData);
    }

    private void reset() {
        i = 0;
        k = 0;
    }

    private void visitChartData(Iterable<Object> chartData) throws IllegalAccessException {
        for (Object currObj : chartData) visitObject(currObj);
    }

    private void visitObject(Object currObj) throws IllegalAccessException {
        for (Field field : currObj.getClass().getDeclaredFields()) visitField(currObj, field);
    }

    private void visitField(Object currObj, Field field) throws IllegalAccessException {
        field.setAccessible(true);
        Object value = field.get(currObj);
        if (value instanceof Map) visitMap((Map) value);
    }

    private void visitMap(Map<?, ?> hm) {
        hm.entrySet().forEach(this::visitEntry);
    }

    private void visitEntry(Map.Entry<?, ?> entry) {
        visitEntryDetails(entry, "y", i, 0, this::incrementI);
        visitEntryDetails(entry, "x", k, 1, this::incrementK);
    }

    private void visitEntryDetails(Map.Entry<?, ?> entry, String string, int index1, int index2, Incrementor incrementor) {
        if ((entry.getKey().toString().equalsIgnoreCase(string)))
            visitMatchingDetails(entry, string, index1, index2, incrementor);
    }

    private void visitMatchingDetails(Map.Entry<?, ?> entry, String string, int index1, int index2, Incrementor incrementor) {
        final String valueAsString = entry.getValue().toString();
        final Long v = anArrayOfObjects[index1][index2];
        assertTrue(Long.parseLong(valueAsString) == v); // check pairs
        System.out.println("Actual " + string + " value - " + valueAsString + " expected value - " + v.toString());
        incrementor.increment();
    }

    @FunctionalInterface
    private static interface Incrementor {
        void increment();
    }

    private void incrementK() {
        k++;
    }

    private void incrementI() {
        i++;
    }
}

You might notice that not a single method contains {} inside.
That's the whole point.
{} are an opportunity to extract.
Good methods do one thing, they do it well and they do it only.
By having {} inside, you loudly declare that your method is doing more than one thing (or in case of try that the language Java is inconsistent because otherwise it would allow for a try or catch or finally without braces).

You're of course free to reformat it to bring back the removed {}, if you like or if there are militant "{}-Pros" around you (I was one of them myself once, not so long ago).
Today I tend to avoid {} to show off "Look Ma, no {}!" - I don't need them anymore.

Unit Testing

The methods in the new class do not need to be private.
They could as well be package default or public, depending on your business logic.
Because they need not be private, you can easily unit test them individually - you can now test your business logic from inside to the out.
The various layers that were already there (nested block structure in your code) have become accessible individually.
Think of an Onion or Matryoshka.

Warning

My names visit* and similar are not very meaningful. They are physical names. I couldn't come up with better names because I have no idea about what your code is doing. I don't know what the map contains.

You should change some or even all of the the visit* method names to something which communicates the intent of your business logic much better.


Measure distance using echo signal from Ultrasonic sensor

raw_ultrasonic_measure measures the duration of an echo staying high. It is not related to the distance in any way, it is just a duration of trig signal.

You need a time elapsed from the beginning of a signal to reception of echo - that is, a duration of echo being low.

In a quick and dirty way,

        signal_start = micros();
        digitalWrite(Trig, HIGH);

        while (digitalRead(Echo) == 0) {
            ;
        }

        echo_received = micros();
        digital_write(Trig, LOW);

        return (echo_received - signal_start) / (2 * speed_of_sound);

In a real world application you would want to debounce echo, provide for a timeout, etc.

You may also want to account for the time taken by a first call to digitalWrite, but I doubt it will make any perceptible difference.

ultrasonic_measure is in fact a loop:

        double value = 0.0;
        for (int i = 0; i < 5; i++) {
            value += raw_ultrasonic_measure(Trig, Echo);
        }
        return value / 5;

One benefit of such approach is an ability to pass a number of samples as a parameter.


Reduce the code in a WHERE clause without using dynamic SQL

You will have to test this carefully, but the following query should work:

WHERE
(
  @Max IS NULL
  OR @Type = 'Products' AND ProductCount > @Max
  OR @Type = 'Vendors'  AND VendorCount  > @Max
  OR @Type = 'Order'    AND OrderCount   > @Max
)
AND
(
  @Min IS NULL
  OR @Type = 'Products' AND ProductCount < @Min
  OR @Type = 'Vendors'  AND VendorCount  < @Min
  OR @Type = 'Order'    AND OrderCount   < @Min
)


Searching for column-indices of a multi-dimensional array that match multiple conditions (one condition per row)

Python is not Java

Not everything needs to be in a class

class MaskOps():

    @staticmethod
    def get_base(shape, value, dtype=int):
        """ This function produces a base-mask, the values of which may be overwritten. """
        if isinstance(value, (float, int)):
            res = np.ones(shape, dtype=dtype) * value
        elif isinstance(value, str):
            res = np.array([value for idx in range(np.prod(shape))]).reshape(shape)
        return res

    @staticmethod
    def alternate_base(shape, key):
        """ This function creates base-masks that consist of one of two value; the value depends on the index input as the parameter key. """
        if key % 2 == 0:
            value = 0.25
        else:
            value = 0.5
        return MaskOps().get_base(shape, value, dtype=float)

MO = MaskOps()

can just be

def get_base(..):
    ...
def alternate_base(...):
    ...

looping

Python has a lot of elegant looping constructs

for idx in range(len(bases)):
    bases[idx][locs[idx]] = 0

for example is not one of them. This can be done with zip

for base, loc in zip(bases, locs):
     base[loc] = 0

Check out this talk (slides) for tips on enumerate, zip, generators etc.

return values, don't print them

When you print the value, it makes it harder to reuse this part of the code in another place. Better would be to split the core_algorithm in different functions all doing their part of the calculation, so you can test each of these parts individually, and decide how to print the result

use numpy  (#1)

You have a lot of numpy arrays that you make from list comprehensions. It would be a lot easier and clearer to vectorize this, and use numpy's large arsenal of native methods

def get_base(shape, value, dtype=int):
    """ This function produces a base-mask, the values of which may be overwritten. """
    if isinstance(value, (float, int)):
        res = np.ones(shape, dtype=dtype) * value
    elif isinstance(value, str):
        res = np.array([value for idx in range(np.prod(shape))]).reshape(shape)
    return res

can be more easily written as

def get_base(shape, value, dtype=int):
    dtypes = {int: int, float: float}
    if not dtype:
        dtype = dtypes.get(type(value), object)
    return np.ones(shape, dtype=dtype) * value

use numpy (#2)

Instead of making this boolean mask yourself, why not just do:

mask = data == [[i] for i in search_value]
collapsed_mask = mask.all(axis=0)
result = data[:, collapsed_mask]


Finding the longest unique sub-string in a string

static int longest_length = -1;

No. Static is useless here and makes you method much less usable. A non-static variable would be better, but actually, why not return a result???

There's no longest_length in Java. Maybe longestLength.

Better, return the substring, the length can be easily obtained from it.

Separated printing and computation, good.

if(index >= str.length()) return;

Spacing (after if). Also according to conventions, you should always use braces (I personally don't).

LinkedHashMap<Character,Integer> map = new LinkedHashMap<Character,Integer>();

Use Java 7 diamonds or Guava's Maps.newLinkedHashMap() to save yourself repeated generics.

You need no linked map.

calc(str,last_index+1);

I find the recursion confusing here. You really do nothing, but a simple loop, so use a loop (Even a goto would be clearer than recursion here).

The algorithm indeed runs in O(n*n), which can be shown with a string like

abcde.... abcde....

where you always run through half of the string. I was assuming an unlimited alphabet here, more precisely the complexity is O(n*alphabetSize) as no runs can be longer than alphabetSize.

A much better O(n) algorithm would keep track of the starting and ending positions. Wherever you see a duplicate, advance the start. Sounds damn simple.


Some notes about your code:

for readability, you should add spaces around operators
you should use with to open files; also, instead of first reading the file to a string and then using json.loads, just use json.load on the file itself
instead of running your own counter with inter, use enumerate
using key=lambda x: x[0] is pointless, it does not affect the sort order at all
you are constantly converting between strings and lists; stick to one representation, e.g. here: crumbs = " ".join(last_crumb) and right in the next line: if len(crumbs.split()) > 0:; instead, just test if last_crumb: or if crumbs:, whichever you prefer
lc[len(lc)-1] is the same as lc[-1]
there's some code duplication in the if/else; try to move that outside
your function seems to miss some of the items, e.g. you never output 1.2.2.4 communication mobile vodafone subscr; this is because you overwrite the ln parameter with ln = len(v); not sure why you need that ln parameter anyway...

Taking those into account, your walk_dict function can be simplified significantly:

def walk_dict(d, mess, new_dict, crumbs):
    lc = list(mess) if mess else ["1"]
    for inter, (k, v) in enumerate(sorted(d.items()), 1):
        lc[-1] = str(inter)
        mess = "".join(lc)
        if isinstance(v, dict) :
            crumbs2 = (crumbs + " " + k) if crumbs else k
            walk_dict(v, mess + '.1', new_dict, crumbs2)
        else:
            crumbs2 = crumbs + " " + k + " " + v
        new_dict[mess] = crumbs2
    return new_dict

But the way you convert mess into a list lc and then replace the last element is still -- quite fitting -- a "mess". Same with the way you are mixing "output parameters" and return values.

Here's how I would do it:

def walk_dict(d, key=None, parent=None):
    res = {}
    for i, e in enumerate(sorted(d), 1):
        k = (key    + "." + str(i)) if key    else str(i)
        p = (parent + " " +     e ) if parent else     e
        if isinstance(d[e], dict):
            res.update(walk_dict(d[e], k, p))
            res[k] = p
        else:
            res[k] = p + " " + str(d[e])
    return res

with open('data.json') as f:
    cat_data = json.load(f)
    new_data = walk_dict(cat_data)
    for v in sorted(new_data):
        print v, new_data[v]


Querying for row elements
The original code queries for elements with tag name tr:

var allRows = table.querySelectorAll("tr");

Just as the code utilizes table methods like insertRow(), the property rows could be used instead:
var allRows = table.rows;

That way there is no DOM query each time the button is clicked.
If there was in fact a need to get all elements with tag name tr, the method Element.getElementsByTagName() could be used, and since it "returns a live HTMLCollection of elements"1 that could happen outside the click handler (e.g. where the other elements fetched by Id are stored). For more information about the differences refer to answers to this post from 2010 which (at the time) claimed “querySelectorAll("a") is a shocking 98% slower than getElementsByTagName("a")”, as well as answers to What is the difference between querySelector and getElementsByTagName? like Quentin's answer plus this jsPerf test.

inline onfocus handler vs Javascript
The markup contains the text input element with the onfocus attribute:

 <input id="input" class="input" type="text" placeholder="Enter here!!!" onfocus="this.value=' ' ">

Instead of specifying the focus handler in the markup, it can be added in the JavaScript. That way there is a separation between the business logic and the markup. One way to do this is to use Element.addEventListener() to add a callback function whenever an event occurs. See the example code below:
input.addEventListener('focus', function(event) {
    input.value = ' '; // could also use event.target instead of input
});

That way the logic of clearing the value is separated from the markup.


Eval is evil: Dynamic method calls from named regex groups in Python 3

Since you're converting user input into your own inner representation before evaluating, this is lesser evil. And sometimes this is the right tool for the job (inspect and pdb make good use of it).

But here, I'd go with simple dictionaries. It allows for automatically building the regexp and you don't really need the name of the capturing group since the dictionary already maps that information:

# Maps allowed characters to actual dice
DIE = {
    's': setback_dice,
    'd': difficulty_dice,
    'a': ability_dice,
    'p': proficiency_dice,
}

# Build the rules to parse user input
REX = ''.join(r'(\d{})?'.format(t) for t in DIE)

to_roll = re.match(REX, dice).groups()
for group in filter(None, to_roll):
    count, type_ = group
    DIE[type_].draw(int(count))

Note the use of filter to "not care about the Nones" and the uppercase variable names for constants.

Also:

you might want to wrap your code into functions to ease reusability and testing;
you might want to use re.compile to improve efficiency;
you might want to come up with a better regexp as this one is very dependant on the order it is written.


extern crate hex;

extern crate is generally not necessary for programs since the 2018 (currently latest) edition of Rust. You should be able to delete this line, provided that edition = "2018" is in your Cargo.toml file.

let ciphertext_bytes = hex::decode(ciphertext).unwrap();

If you change .unwrap to .expect("failed to decode ciphertext") then there'll be a little more information in the error message. Of course, for a well-made command line program, you'd want to print your own better-formatted error message, instead of a Rust "panic" error.

fn find_xor_key(ciphertext: &Vec<u8>) -> u8{

Accepting &Vec<u8> is usually overly restrictive because it requires the caller to have constructed a Vec, whereas if you change the type to &[u8] they can pass any slice of bytes. This will work without needing to change main, because Vec derefs to a byte slice.
The same applies to get_score's parameter, but you'll need to tweak a couple things to make that work, like giving xored_vec the explicit type Vec<u8> and changing byte as char to *byte as char.

    let ideal_frequencies: HashMap<char, f32> = [
...
    ].iter().cloned().collect();

This is basically a constant, so it'd be nice if we can compute this hash map only once rather than every time we check a score. We can do that with the once_cell crate, which will hopefully soon become part of the standard library. Like this:
static IDEAL_FREQUENCIES: Lazy<HashMap<char, f32>> = Lazy::new(|| [
    ('E', 11.1607),
    ...
].iter().cloned().collect());

for byte in text.clone(){

Use text.iter() instead of text.clone(); it avoids allocating a copy. In general, where both are available, .into_iter() consumes the structure and iterates over its elements by value (moves them), and .iter() does not consume the structure but iterates over references to its elements instead.

let char_rep: char =  byte as char;
if !char_rep.is_ascii(){

You can just use if !byte.is_ascii() { here.

let chars: Vec<char> = text.iter().cloned().map(|x|x as char).collect();
let frequencies: HashMap<char, f32> = calculate_frequencies(&chars.into_iter().collect::<String>());

.cloned().map(|x|x as char) can be written as .map(|x| *x as char).
You're collecting into chars and then immediately iterate to convert it to a String; that isn't necessary because you can just write
calculate_frequencies(&text.iter().map(|x| *x as char).collect::<String>())

But, there's a bigger point: text was already an &[u8], and if we want a &str out of that, that's just std::str::from_utf8.
calculate_frequencies(std::str::from_utf8(text).unwrap())

(.unwrap() will never fail here because we already checked that every byte is ASCII, so it cannot be invalid UTF-8.)

Your loop over the frequencies has several unnecessary &s, and also looks up in the hash map twice instead of once; here's both fixed:
for (letter, frequency) in frequencies.iter() {
    if let Some(ideal_frequency) = IDEAL_FREQUENCIES.get(letter) {
        if (frequency - ideal_frequency).abs() <= 10.0 {
            score += 1;
        }
    }
}

fn calculate_frequencies(text: &str) ->HashMap<char, f32>{

If we want to optimize for performance, which a real code-breaking tool would want to do, then this function should be accepting &[u8], since the only thing it does with the str is split back to characters, and we know all the characters are ASCII at this point. But for more general idiomatic programming, taking &str is fine.

let mut frequencies: HashMap<char, f32> = HashMap::new();
let mut letter_counts:HashMap<char, i32> = HashMap::new();

You can leave out the type declarations here and they will be inferred.

let text_upper = text.to_ascii_uppercase();
for c in text_upper.chars(){

This allocates a String of uppercase unnecessarily; we might as well do it per-character instead:
for c in text.chars() {
    let c = c.to_ascii_uppercase();

(Note, however, that this strategy does not work for Unicode-aware uppercasing, where one char may occasionally become several.)

This is not a matter of Rust idiom at all, but I notice that frequencies is identical to letter_counts except for the values getting scaled. So, we can reuse a single HashMap instead of duplicating it:
fn calculate_frequencies(text: &str) ->HashMap<char, f32>{
    let count_to_frequency_scale = 100.0 / text.len() as f32;

    let mut counts = HashMap::new();
    for c in text.chars() {
        *counts.entry(c.to_ascii_uppercase()).or_insert(0.0) += 1.0;
    }

    // Rescale counts to frequencies
    for count in counts.values_mut() {
        *count *= count_to_frequency_scale;
    }
    counts
}

Note: Using f32 instead of i32 for counting does not introduce any floating-point error, for reasonable string lengths: f32 exactly represents all integers up to 224 - 1 = 16,777,216. (However, there would be accumulated error if we tried to apply count_to_frequency_scale while counting instead of after.)
If it didn't happen to be possible to reuse the same map, I'd be suggesting using iterators to do the transformation instead:
letter_counts
    .into_iter()
    .map(|(key, count)| (key, count as f32 * count_to_frequency_scale))
    .collect()

Here's your code with all of my suggestions, and also formatted with rustfmt. I haven't tested it because I was working in the Rust Playground which doesn't include the hex crate in its available libraries.
extern crate hex;
use once_cell::sync::Lazy;
use std::collections::HashMap;

#[allow(dead_code)]
fn main() {
    let ciphertext = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736";
    let ciphertext_bytes = hex::decode(ciphertext).unwrap();
    let xor_key = find_xor_key(&ciphertext_bytes);
    println!(
        "{}",
        ciphertext_bytes
            .iter()
            .map(|x| (x ^ xor_key) as char)
            .collect::<String>()
    );
}

fn find_xor_key(ciphertext: &[u8]) -> u8 {
    let mut max_score = 0;
    let mut best_key = 0;
    for xor_key in 1..255 {
        let xored_vec: Vec<u8> = ciphertext.iter().map(|x| x ^ xor_key).collect();
        let score = get_score(&xored_vec);
        if score > max_score {
            max_score = score;
            best_key = xor_key;
        }
    }
    println!("{}", max_score);

    best_key
}

fn get_score(text: &[u8]) -> u8 {
    for byte in text.iter() {
        if !byte.is_ascii() {
            return 0;
        }
    }
    let mut score = 1;
    let frequencies = calculate_frequencies(std::str::from_utf8(text).unwrap());

    for (letter, frequency) in frequencies.iter() {
        if let Some(ideal_frequency) = IDEAL_FREQUENCIES.get(letter) {
            if (frequency - ideal_frequency).abs() <= 10.0 {
                score += 1;
            }
        }
    }
    score
}

fn calculate_frequencies(text: &str) -> HashMap<char, f32> {
    let count_to_frequency_scale = 100.0 / text.len() as f32;

    let mut counts = HashMap::new();
    for c in text.chars() {
        *counts.entry(c.to_ascii_uppercase()).or_insert(0.0) += 1.0;
    }

    // Rescale counts to frequencies
    for count in counts.values_mut() {
        *count *= count_to_frequency_scale;
    }
    counts
}

static IDEAL_FREQUENCIES: Lazy<HashMap<char, f32>> = Lazy::new(|| {
    [
        ('E', 11.1607),
        ('M', 3.0129),
        ('A', 8.4966),
        ('H', 3.0034),
        ('R', 7.5809),
        ('G', 2.4705),
        ('I', 7.5448),
        ('B', 2.0720),
        ('O', 7.1635),
        ('F', 1.8121),
        ('T', 6.9509),
        ('Y', 1.7779),
        ('N', 6.6544),
        ('W', 1.2899),
        ('S', 5.7351),
        ('K', 1.1016),
        ('L', 5.4893),
        ('V', 1.0074),
        ('C', 4.5388),
        ('X', 0.2902),
        ('U', 3.6308),
        ('Z', 0.2722),
        ('D', 3.3844),
        ('J', 0.1965),
        ('P', 3.1671),
        ('Q', 0.1962),
    ]
    .iter()
    .cloned()
    .collect()
});
```


import

why import product within your method, and not in the module scope?

instantiation

There is just no reason to instantiate the list in

choices = list(product(range(1, faces+1), repeat=dice))

when you just iterate over it.

As noted by @JordanSinger, this takes a huge toll on memory, while using it as an iterable suffices

numpy alternative

a = sum(
    np.meshgrid(
        *(np.arange(1, faces + 1, dtype="uint8") for _ in range(dice)),
        copy=False
    )
)
(a == number).sum()

but for larger number of dice and faces this runs into MemoryError too

alternative

The integer value of True is 1. So instead of keeping a counter, and incrementing it each time there is a match, you can do:

def poss_combinations(dice, faces, number):
    choices = product(range(1, faces+1), repeat=dice)
    return sum(sum(roll) == number for roll in choices)

But even this will take ages for 10**10 combinations. Better would be to use a analytical formula like this one

alternative 2

A first alternative, is instead of taking the product, using itertools.combination_with_replacement to get all the combinations of dice rolls. For 10 10-faced dice, this is sum(1 for _ in combinations_with_replacement(range(10), 10)) or 92378. This is a much better number to work with that 10**10

The next step is to check which combinations combine to numbers, and then calculate how much of these combinations are possible link

from collections import Counter
from functools import reduce
from math import factorial
from operator import mul

def product_math(iterable):
    return reduce(mul, iterable, 1)

def combination_permutations(combination):
    c = Counter(combination)
    return factorial(sum(c.values())) / product_math(
        factorial(i) for i in c.values()
    )

calculates the number of possible permutations of a combination

def poss_comb_permutations(dice, faces, numbers):
    return sum(
        combination_permutations(combination)
        for combination in combinations_with_replacement(
            range(1, faces + 1), dice
        )
        if sum(combination) == numbers
    )

Then uses this to calculate the number of matching dice rolls.

All 3 methods arrive at the same result for

dice = 7
faces = 7
number = 20


Structure of website columns and navigation

Don't worry about wrapping your content too much if the style cannot be achieved without it. If it can, the extra wrap may be overkill.
Your markup relies a lot on the <article> where it may not be necessary. For instance, you put one <article> tag into another, which is odd. You also put and <article> tag into the <header>, which is also odd.

If you want simple containers, I would recommend you stick with <div>s with semantic class attributes. They have been around for a while and used for wrapping other tags. They are the tried and true method and their lack of semantic meaning will not confuse the reader or crawler.


CONST is not a name; it doesn't convey any meaning. Call it something like rads_per_degree. If you feel you need to comment on the value, better do the calculation explicitly (take advantage of \$\pi\$ being defined for you in cmath):

const double rads_per_degree = M_PI / 180;

Each time you rotate, you recalculate radian measure, sin and cos. Within the test case these values do not change. You may safely precompute them:

double rads = rads_per_degree * angle;
double sin = std::sin(rads);
double cos = std::cos(rads);
while (v--) {
    do_math(x, y, sin, cos, L);
}

I am not sure why you special cased small values.
getDouble is somewhat dubious. It would've make sense to have such a function to sanitize input. As written, it is meaningless. Also, you should not read integer as double.


From the comments it sounds like you don't really need to create a new list.  Using generators will avoid the overhead of ever building a new list.

Just use this pattern:

def filterLibrarySingle(self, filterField, filterMethod, filterValue1, filterValue2=None):
    if filterMethod == 'eq':
        for cas in self.Lib:
            if getattr(cas, filterField) == filterValue1:
                yield cas
    ...

And you can call the method such as:

for item in filterLibrarySingle('my_field', 'eq', 'George'):
    do_stuff(item)

If this doesn't work, then you may have to consider designing a more advanced structure to store your data so that your searches are not \$O(n)\$ but rather \$O(\log{}n)\$.


Get all followers and friends of a Twitter user

You should use is to compare to None, as that's faster.

def is_user_in_db(user_id):
    return get_user_from_db(user_id) is None

You can also use list concatenation rather than list.extend as it's slightly faster and there's no benefit to extend in this context. I also second the recommendation to use enumerate rather than having a manually incremented number in a for loop.

def get_followers(user_id):
    users = []
    page_count = 0
    for i, user in enumerate(tweepy.Cursor(api.followers, id=user_id, count=200).pages()):
        print 'Getting page {} for followers'.format(i)
        users += user
    return users

When you have a local variable here, use it instead of a dictionary call. It's quicker to access than a key.

screen_name = user['screen_name']
print 'Processing user : {}'.format(screen_name)

You can also collapse these lines by assing the results of the function calls directly.

    user['followers_ids'] = get_followers_ids(screen_name)
    user['friends_ids'] = get_friends_ids(screen_name)

You can make a list comprehension out of users_to_add, it's a single line of code that more efficiently creates a list based on a for loop-like construct. So this:

    users_to_add = []
    for follower in get_followers(screen_name):
        if not is_user_in_db(follower.id):
            users_to_add.append(follower._json)

    for friend in get_friends(screen_name):
        if not is_user_in_db(friend.id):
            users_to_add.append(friend._json)

Can be turned into this:

    users_to_add = [follower._json for follower in
            get_followers(screen_name) if not is_user_in_db(follower.id)]
    users_to_add += [friend._json for friend in
            get_friends(screen_name) if not is_user_in_db(friend.id)]

Also, it's more efficient to call dictionary keys, assuming they're there and handle the exception if they're not, like so:

try:
    process_user(doc['user'])
except KeyError:
    pass

try:
    process_user(doc['retweeted_status']['user'])
except KeyError:
    pass

You could replace pass with something else if you'd like, but this is more efficient as the if statement in your script would check the dictionary to see if a key exists, and then check it again to get the actual value attached to the key. The try except way only checks once, and moves on if it gets nothing.

One final note, you'd be surprised how expensive frequent print calls are. You have ones running in loops. I don't know how often the loops run, but if you are experiencing sluggishness, try removing them to see what difference it makes. Feedback is obviously important, but speed is also important.


While these may not be any shorter or more efficient than existing answers, perhaps with a slightly different approach they still bring something to the table and might be considered a little less 'ugly'.

Essentially the GetRanges function I've written does the following:

Take a parameter-supplied array of numbers ($aNumbers), remove any duplicates from the array and then sort them numerically lowest to highest.
We next create a multi-dimensional array ($aGroups) and working sequentially through the array of numbers ($aNumbers): Except for the first number which we just add to $aGroups to get us started, for each consecutive number $i > 0, if the previous number $aNumbers[$i-1] is equal to the current number minus 1 $aNumbers[$i] - 1 then the current number is added to the same group because its consecutive and belongs to that range, otherwise the current number is added to $aGroups as a new sub-array with one entry array( $aNumbers[$i] ).

For options 2 and 3 where the function is expanded upon for a simple array:

A new array ($aRanges) is created and for each $aGroups record, if the first entry of the sub-array is the only entry then a new entry is added to $aRanges for just this number, otherwise a new entry is added to $aRanges specifying the first number in the range followed by a hyphen followed by the last number in the range.

For option 3 where the function is expanded upon to return a string:

The implode function is used to create a comma-separated list of all the entries in the $aRanges array and return this as a string.

Option 1: If you want your function to return a multi-dimensional array:

<?php
function GetRanges( $aNumbers ) {
  $aNumbers = array_unique( $aNumbers );
  sort( $aNumbers );
  $aGroups = array();
  for( $i = 0; $i < count( $aNumbers ); $i++ ) {
    if( $i > 0 && ( $aNumbers[$i-1] == $aNumbers[$i] - 1 ))
      array_push( $aGroups[count($aGroups)-1], $aNumbers[$i] );
    else
      array_push( $aGroups, array( $aNumbers[$i] ));
  }
  return $aGroups;
}

$aNumbers = array( 1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 20, 24 );
print_r( GetRanges( $aNumbers ));

  Output:

Array (
  [0] => Array ( [0] => 1, [1] => 2, [2] => 3, [3] => 4, [4] => 5, [5] => 6 )
  [1] => Array ( [0] => 10, [1] => 11, [2] => 12, [3] => 13 )
  [2] => Array ( [0] => 20 )
  [3] => Array ( [0] => 24 )
)

Option 2: If you want your function to return a simple array:

<?php
function GetRanges( $aNumbers ) {
  $aNumbers = array_unique( $aNumbers );
  sort( $aNumbers );
  $aGroups = array();
  for( $i = 0; $i < count( $aNumbers ); $i++ ) {
    if( $i > 0 && ( $aNumbers[$i-1] == $aNumbers[$i] - 1 ))
      array_push( $aGroups[count($aGroups)-1], $aNumbers[$i] );
    else
      array_push( $aGroups, array( $aNumbers[$i] ));
  }
  $aRanges = array();
  foreach( $aGroups as $aGroup ) {
    if( count( $aGroup ) == 1 )
      $aRanges[] = $aGroup[0];
    else
      $aRanges[] = $aGroup[0] . '-' . $aGroup[count($aGroup)-1];
  }
  return $aRanges;
}

$aNumbers = array( 1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 20, 24 );
print_r( GetRanges( $aNumbers ));

  Output: Array ( [0] => 1-6, [1] => 10-13, [2] => 20, [3] => 24 )

Option 3: If you want your function to return a string:

<?php
function GetRanges( $aNumbers ) {
  $aNumbers = array_unique( $aNumbers );
  sort( $aNumbers );
  $aGroups = array();
  for( $i = 0; $i < count( $aNumbers ); $i++ ) {
    if( $i > 0 && ( $aNumbers[$i-1] == $aNumbers[$i] - 1 ))
      array_push( $aGroups[count($aGroups)-1], $aNumbers[$i] );
    else
      array_push( $aGroups, array( $aNumbers[$i] ));
  }
  $aRanges = array();
  foreach( $aGroups as $aGroup ) {
    if( count( $aGroup ) == 1 )
      $aRanges[] = $aGroup[0];
    else
      $aRanges[] = $aGroup[0] . '-' . $aGroup[count($aGroup)-1];
  }
  return implode( ',', $aRanges );
}

$aNumbers = array( 1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 20, 24 );
echo( GetRanges( $aNumbers ));

  Output:
  1-6,10-13,20,24


Well, I always start with using a main block. It's just a good habit to have.

Name your constants. What if you wanted the change the number the user was supposed to guess to, say, 5? You already have at least two places in the code where 0 shows up, and what you actually mean by that is "the target value". Give it a name and use that name.

target = 0

while guess != target: # ...

You're checking the game-end logic twice, once in the outer while loop, once in the inner if check. Only do so in one place. E.g., make the outer loop while True: or, better yet, for _ in range(max_num_guesses): with an explicitly set maximum number of guesses. Then, inside the if statement that checks if the user got the answer right, just break to exit the loop.

Now, about what you particularly ask about: computing the sum/mean/count of the users' guesses. Your current approach scatters the logic of what you're trying to do: summation happens on one line, counting on another, division on another... this code sample isn't big, but already this goal is scattered across your code. It'd be a lot cleaner if we dealt with all those similar things in one place. To do this, let's just keep track of the guesses inside the loop, then later, we'll do all the relevant computations with them. Something like:

target = 0
guesses = []

while True:
    print("Guess the number: ")
    guess = int(input())
    guesses.append(guess)

    if guess == target:
        break

    print("Nope.")

print(f"Attempts: {len(guesses)}")
print(f"Total sum of guesses: {sum(guesses)}")
print(f"Average guess: {sum(guesses) / len(guesses)}")

This snippet doesn't do exactly what your code does, but hopefully it gives you an idea for how you can keep different chunks of your code focused on different purposes, and thus keep each bit clean and keep the logic simple. See how the while-loop section is solely focused on running the game logic, and the print section is solely focused on what details you want to print back to the user. The only crossover is the the guesses.append(guess) line in the loop, which just says "I'll want this info later" and let you, later, figure out exactly what you want to do. E.g., let's say you wanted to report the median guess, or how many guesses were above versus below the target; these are easy to add later if we have a list of guesses, but would add yet more fluff to the loop if we tried to keep track as we went along. Note that, since you're just keeping track of user input, this list is never expected to get so big that counting and summing it is worth bothering about; even if you want to report this value in each loop iteration, just compute it each time rather than trying to calculate things incrementally.

Oh, and finally, while I'm all for the try-and-fail when it makes your code cleaner, this probably isn't such an occasion. I'd consider:

if count > 1:
    average = (total_sum / (count - 1))
    print("Average number:", average)
else:
    print("No average")

or even:

print(f"Average number: {total_sum / (count - 1)}" if count > 1 else "No average")

to be cleaner than using a try/except ZeroDivisionError here.

(PS: Note the use of f-strings rather than relying on the print function to append things to strings... that's also a good habit, though not a significant improvement in this particular case.)


Tarjan's strongly connected components algorithm

There is no reason to use String as keys in graph. By default an object can be used as a key in a hashmap based on it's uniqueness.

There is no reason that the values have to be ArrayLists instead just use List.

HashMap<Node, List<Node>> graph = new HashMap<>();

This can clean up the init code as you don't have to do new ArrayList<> and can instead just pass Arrays.asList(nodes.get("a")) directly.

Though having said all that you can just put the List of neighbours straight in the Node and not deal with having to look it up in strongConnect.


You should generally avoid List.append because appending to a singly-linked list is quite inefficient.

I think your getVerse function is probably doing too much. You can have a function to get a line at a time which is just int -> string

Recursion can be avoided here if you switch to a list comprehension (the for...in syntax). Recursion is rarely needed in F#.

Even folding can be avoided here as it's simpler to use String.concat.

With all of these changes and a couple more:

let ordinalSuffix = function 1 -> "st" | 2 -> "nd" | 3 -> "rd" | _ -> "th"

let preamble num =
    sprintf "On the %i%s day of Christmas, my true love gave to me" num (ordinalSuffix num)

let line num =
    match num with
    | 12 -> "12 drummers drumming"
    | 11 -> "11 pipers piping"
    | 10 -> "10 lords a-leaping"
    | 9 -> "9 ladies dancing"
    | 8 -> "8 maids a-milking"
    | 7 -> "7 swans a-swimming"
    | 6 -> "6 geese a-laying"
    | 5 -> "5 golden rings"
    | 4 -> "4 calling birds"
    | 3 -> "3 French hens"
    | 2 -> "2 turtle doves, and"
    | _ -> "A partridge in a pear tree"

let verse num =
    preamble num :: [ for i in num .. -1 .. 1 -> line i ]
    |> String.concat "\n"

[1 .. 12] |> List.map verse |> String.concat "\n\n" |> printfn "%s"


There are a few things you can do to reduce repetition in your code. The first would be encapsulating your new Node<T> into a method.

impl<T> Node<T> {
    fn new(elem: T) -> Self {
        Self {
            elem,
            left: None,
            right: None,
        }
    }
}

Then all the constructions of Node in add can be replaced with Node::new(elem).

Another thing that can reduce verbosity is having current be an actual (boxed) node rather than an option. Right now you maintain the invariant that current is the Some variant of an Option<&mut Box<Node<T>>> (Link<T>). By instead keeping the &mut Box<Node<T>>, it'll allow you to reduce the number of unwraps. Conceptually, this means that we're expressing the invariant using the type system.

For example, to initialize current,

let mut current;
match self.root {
    None => {
        self.root = Some(Box::new(Node::new(elem)));
        return;
    }
    Some(ref mut node) => {
        current = node;
    }
}

(matching on Some(ref mut node) makes node a mutable reference - there are some other ways to get the same effect, but this is the clearest).

Having this allows you to change the later blocks to

if elem < current.elem {
    if current.left.is_none() {
        current.left = Some(Box::new(Node::new(elem)));
        break;
    } else {
        current = current.left.as_mut().unwrap();
    }
}

My last major suggestion is to use matching to get rid of all the unwrapping. Blocks like

if current.left.is_none() {
    current.left = Some(Box::new(Node::new(elem)));
    break;
} else {
    current = current.left.as_mut().unwrap();
}

are just the poor man's match statement. They can be replaced by

match current.left {
    None => {
        current.left = Some(Box::new(Node::new(elem)));
        break;
    }
    Some(ref mut node) => {
        current = node;
    }
}

(again, ref mut node means we're capturing a mutable reference).

This could more succinctly be expressed using if let.

if let Some(ref mut node) = current.left {
    current = node;
} else {
    current.left = Some(Box::new(Node::new(elem)));
    break;
}

Now for some extra things. First, as I mentioned in the comments, the code as written handles duplicates by placing them to the right. This isn't necessarily what you want, but it's easy to change. The trait Ord provides a cmp method that has three possible outputs: Less, Greater or Equal. By doing a match on the output of cmp, we can handle all three.

match elem.cmp(&current.elem) {
    std::cmp::Ordering::Less => {
        //...
    }
    std::cmp::Ordering::Equal => break,
    std::cmp::Ordering::Greater => {
        //...
    }
}

If you don't want to type out the whole names, you could do use std::cmp::Ordering::*; inside the fn add block (or wherever else, but it's best to keep the scope small).

This suggestion would be a pretty major rework of your code, but it leads to a much more elegant solution. As I said before, you maintain the invariant that current is a Some variant. I suggested that you could keep a &mut Box<Node<T>> instead so that the invariant is expressed in the type of current. What you can do instead is not try to keep that invariant at all, but instead check whether current is Some or None at the start of the loop. Then you wouldn't need the initial test on self.root.

fn add(&mut self, elem: T) {
    let mut current = &mut self.root;
    loop {
        match current {
            Some(node) => {
                // check how elem compares to node.elem
                // assign node.left/right to current as appropriate (or break)
            }
            None => {
                // set the data behind `current` to a new node.
                // i.e. `*current = ...`
            }
        }
    }

Finally, just a fairly minor thing. Don't forget to run cargo fmt and cargo clippy. cargo fmt will make your code more readable to other Rust programmers and keep things in a consistent style. cargo clippy will give you a few helpful tips for making your code more idiomatic and sometimes help avoid logic errors.


Be consistent

The most important advice I could give you is be consistent. Be consistent with your naming convention, the placement of brackets and everything else. Why ? Because even if you're doing something wrong you will be predictable, and that is what make things faster when reviewing.

   if (size <= 0) {
        System.out.println("Please enter a valid String");
   }

vs

 if (newSize == 1)
        return;

Same situation, an if condition and one line of code if the condition is good. Why one have brackets and the other one don't have it ? In this particular case, always use brackets. It's more readable, if you add a line of code you don't have to add brackets and it will probably reduce the chance to have bugs.

Constructor

public Anagrams(String anagramString, int size)

You already using String as parameter, why do you have size ? When you call your constructor, you're passing str.lenght(). I suggest that you drop the second argument and just call the length directly in your constructor.

public Anagrams(String anagramString) {
    if (size <= 0) {
        System.out.println("Please enter a valid String");
    }
    chArray = anagramString.toCharArray();
    this.size = anagramString.lenth();

}

Another important point, you're checking if the size <= 0 and print that you must enter a valid String, but you don't do nothing else. The program will go on in an invalid state. You could throw an exception that specify that the length of the String must be greater than 0.

Comments

Never leave // TODO Auto-generated method stub comments. It's just noise in the code, and could lead to people thinking that your code is somewhat not finished.


Stack - Implemented as Singly Linked List

Your stack_search function re-implements loop over your linked-list. Instead of that you can use your __iter__ itself to keep in DRY. Plus it should True or False instead of 1 and 0.

The Pythonic way will be implement __contains__ to check if your container type contains an item. Then you could simply do 'a' in my_stack.

def __contains__(self, value):
    return value in (node.data for node in self)

Instead of length method implement __len__. This will work with Python's built-in len().

Plus after defining this you won't need the method is_empty either as __len__ can be used to check for falsyness: if my_stack: .... You could also define __bool__ based on self.head for checking falsiness instead of using __len__, but it would be redundant in my opinion.
pop() should raise an exception when the stack is empty, for example list.pop, dict.pop, deque.pop all raise some error for it.
Stack().peek() currently raises an AttributeError. Instead of that you should be raising some custom exception when the stack is empty.


The code looks OK for what it does so far, but there are some things you might want to do to improve it:

Always use {} for production rules

It's not technically wrong to simply have printf(...) to the right of a rule, but when your lexer gets more complex (and when you start also using a parser) you may find it easier to troubleshoot if you always use {} to enclose production rules -- even empty ones.

Think about explicitly handling whitespace

It's very common for a parser to need to ignore whitespace. If that's the case, it's usually good to do so explicitly with a rule just above the error-handling rule(s) I mention below.

[ \t\n]+   { /* ignore whitespace */ }

Consider a "catch-all" rule for illegal tokens

Right now, pretty much any random character will be accepted.  This might be fine, but especially while you're learning, you may find it useful to put a catch-all rule at the bottom of your list of rules:

.   { printf("Bad character: %s\n", yytext); }

Consider adding support for multiline comments

As your original (pre-edit) code had it, handling multiline comments is different but not too difficult.  You can add this to your definitions (the first part of a flex file):

%x c_comment

Then add these rules to the rules section (second part of a flex file):

"/*"   { BEGIN(c_comment); }
<c_comment>[^*]*        { }
<c_comment>"*"+[^*/]*   { }
<c_comment>"*/"         { printf("Ignored a multiline comment\n"); BEGIN(INITIAL); }

This defines a start condition called c_comment and switches into that condition when it finds the opening pair of characters for a comment.  The next rule ignores everyting that is not a * character. The next line ignores all * characters that are not followed by a /.  The point to these two rules is to match as many characters as possible.  For performance reasons, you would generally want to write your lexer so that it matches strings that are as long as possible for each rule.  This helps the lexer go faster.

Finally, the last rule finds the closing pair of characters and switches back into the initial context.  You will also often see BEGIN(0) for that -- the statements are identical in function, but I prefer the more verbose BEGIN(INITIAL) form because I think it's easier to understand.


Java class to compute and get a MD5 hash as a string

THe most striking issue I can see in your code is that you're severely limited in the size of files you can compute the hash on. This line of code is particularly jarring:

md.update(Files.readAllBytes(path));

You read the entire file in to memory... which limits you to two things:

the size of your file is limited to the size of your memory ... unless
you have lots of memory, but the file is >2GB at which point you can't create a larger array of bytes.

The reason that the MessageDigest methods contain the update method, is to deal with larger files, and allow you to hash them in parts.

I would use this as an opportunity to learn the somewhat older NIO features: Channels, and Buffers.

Consider the code:

try (MessageDigest md = MessageDigest.getInstance("MD5")) {
    try (FileChannel fc = FileChannel.open(Paths.get(filePath))) {
        long meg = 1024 * 1024;
        long len = fc.size();
        long pos = 0;
        while (pos < len) {
            long size = Math.min(meg, len - pos);
            MappedByteBuffer mbb = fc.map(MapMode.READ_ONLY, pos, size);
            md.update(mbb);
            pos += size;
        }
    } catch (IOException ioe) {
        ....
    }
    byte[] hash = md.digest();
    .....
} catch ( NoSuchAlgorithmException nsae) {
    ....
}

The advantage of the above code is that is plays much closer to the operating system. In theory, it should be the fastest possible way for a Java program to read the file, and it should never transfer the actual file content in to the Java memory space. It removes at least one data copy between the file represented in the OS on disk, and the copy in memory.

There is no limit to the size of file you compute the hash on.


Order a list of tuples or a NumPy array in a specific format

This is really a graph problem! Draw a graph with a vertex for every number in your list, and an edge between vertices \$a\$ and \$b\$ if there is a pair \$(a, b)\$ or \$(b, a)\$ in your list:

What you want to do is to find a path in this graph that visits all the edges. Such a path is known as an Eulerian path. Your condition that each number appears exactly twice in the list means that the path must return to the original vertex: that makes it an Eulerian cycle.

To find this cycle, we must first represent the graph using a suitable data structure. Here we can use the adjacency list representation (really, adjacency set):

from collections import defaultdict

def graph(edges):
    """Given a list of edges, return a map from vertex to a set of
    adjacent vertices.

    >>> graph([(1, 2), (1, 3), (3, 4), (2, 4)])
    defaultdict(<class 'set'>, {1: {2, 3}, 2: {1, 4}, 3: {1, 4}, 4: {2, 3}})

    """
    g = defaultdict(set)
    for v, w in edges:
        g[v].add(w)
        g[w].add(v)
    return g

Then, to find the path, we can use Hierholzer's algorithm. This is really simple: we just pick a starting vertex and then repeatedly pick any unvisited edge from that vertex. Your condition that each number appears exactly twice in the list of edges means that the algorithm can't get stuck: there are exactly two edges meeting each vertex, so having gone in on one we can go out on the other:

def eulerian_path(edges, v):
    """Generate an Eulerian path over the given collection of edges,
    starting at the vertex v.

    >>> list(eulerian_path([(1, 2), (1, 3), (3, 4), (2, 4)], 1))
    [(1, 2), (2, 4), (4, 3), (3, 1)]

    """
    g = graph(edges)
    while True:
        try:
            w = g[v].pop()
        except KeyError:
            return
        g[w].remove(v)
        yield v, w
        v = w

What might happen, however, is that your data contains multiple disjoint cycles. For example if the input is:

[(1, 2), (2, 3), (3, 1), (4, 5), (5, 6), (6, 4)]

then this corresponds to the graph:

The eulerian_path algorithm only finds one of the cycles. What should you do in ths case? Stop at the end of the first cycle? Keep going and find all the other cycles? Maybe this can't happen in your problem, so raise an error? You didn't explain what your problem really is, so I can't tell you what the right thing is to do in this case.

Update

If you're determined to stick to NumPy, then consider using the Compressed Sparse Graph Routines. The idea is to use scipy.sparse.csr_matrix to convert your array into a CSR matrix:

>>> edges = np.array([(1, 2), (1, 3), (3, 4), (2, 4)])
>>> m = scipy.sparse.csr_matrix((np.ones(len(edges)), (edges[:,0], edges[:,1])), shape=(5, 5))

and then call scipy.sparse.csgraph.depth_first_order to get the vertices on the Eulerian path:

>>> scipy.sparse.csgraph.depth_first_order(m, 1, False)[0]
array([1, 2, 4, 3], dtype=int32)

If you need to turn this array of vertices back into an array of edges (as in the OP), you could use numpy.vstack and numpy.roll, like this:

>>> np.vstack((vertices, np.roll(vertices, -1))).T
array([[1, 2],
       [2, 4],
       [4, 3],
       [3, 1]], dtype=int32)


The multithreading model to clean ConcurrentQueue in C#

I think the EventfulConcurrentQueue was not designed for this use case.
From the consumer perspective:

Things that are not in use

IsEmpty
Enqueue
ItemEnqueued
ItemDequeued

Things that are missing

DequeueAtMostNItems
WaitUntilThereAreEnoughItems

After I removed the not used things and added the missing ones the class would look like this:
public sealed class EventfulConcurrentQueue<T>
{
    private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();

    public List<T> DequeueAtMostNItems(int n)
    {
        List<T> result = new();
        T current;
        do
        {
            if(_queue.TryDequeue(out current))
                result.Add(current);
        } while (current != null && result.Count <= n);

        return result;
    }

    public async Task WaitUntilThereAreEnoughItems(int numberOfItems)
    {
        while (_queue.Count < numberOfItems)
        {
            await Task.Delay(100);
        }
        return;
    }
}

With these methods you are embracing encapsulation. The operation and data are next to each other. And with this approach you don't have to expose anything internal, so the information hiding aspect is covered as well.
If you stick with this implementation then I would suggest a renaming, because the ConcurrentQueue now becomes an implementation detail.
The usage could be simplified like this:
while (true)
{
    await PacketQueue.WaitUntilThereAreEnoughItems(chunkSize);

    var chunk = PacketQueue.DequeueAtMostNItems(chunkSize);
    DataTable toBeInserted = DataHelper.CreateBulkCopyDataTable();
    chunk.ForEach(row => toBeInserted.Rows.Add(Guid.NewGuid(), row.AtTime, row.GPSTrackerID, row.PacketBytes));

    using var bulkCopy = ...
}


React Smart and Dumb Components separation query

Seems like you got a good start.

Consider refactoring components that do not keep state into a "functional component". More about functional components here. This is a simple JavaScript arrow function that returns what you would like the component to render, based on your props. The function will take the prop-object as an argument. In your case it would become:

const Child = (props) => (

I said {props.greeting} {props.count} times

)

Or even simpler using destructuring from Ecmascript 2015. Notice that we can retrieve the attributes of the prop-object directly in the function parameters.

const Child = ({greeting, count}) => (

I said {greeting} {count} times

)

I think your parent component is fine. You are separating the concerns of the buttons and text output neatly and there is no need to move the buttons into the Child component. This is obviously a simple example, in more complex cases it might make sense to encapsulate the elements inside another component in order to prevent re-rendering or because of functional cohesion. In this case it would perhaps be overkill.


Automatically indent a whole block of text into str.format

Could textwrap do some of the job?

Particularly the dedent and indent function?  You will still need to count the number of tabs you want, but the rest will be done.


Parsing airline reservation using JS regular expressions

You don't need a loop, you can use the string's match method, but in order to get only the matched group you have to use a lookbehind, which javascript's implementation of regex doesn't support, but, it does support a lookahead, so basically, you could reverse it, reverse all the matches and filter out empty strings to get the reservation codes. Since you only have a single match for the names you don't need a loop for that either, assuming there will always be a match, so you can just use exec and pop the result off the end..

const str = `30 OCT 2017  04 NOV 2017
    Distance (in Miles):500
    Stop(s): 0
    Distance (in Miles):500
    Stop(s):0
    TRIP TO KRAKOW, POLAND
    PREPARED FOR
    DOE/JANE MRS
    APPLESEED/JOHN MR
    RESERVATION CODE   UVWXYZ
    AIRLINE RESERVATION CODE DING67 (OS)
    AIRLINE RESERVATION CODE HDY75S (OS)`;

var r1 = / (.*)(?= EDOC NOITAVRESER ENILRIA)/g,
    r2 = /PREPARED FOR([^]*?)RESERVATION/g;

const rev = s=>s.split('').reverse().join('').trim();

let x = r2.exec(str).pop();
let m = rev(str).match(r1).map(rev).filter(w=>w.length);

console.log(x);
console.log(m);


Award Budget Cuts implementation in Java

I believe that the problem in the first place is not well defined (or we are trying to solve a different problem). And I mean...

The problem states the following:

  write a function findGrantsCap that finds in the most efficient manner a cap such that the least number of recipients is impacted and that the new budget constraint is met

So it focuses on the recipients impacted and not on the amounts.

e.g

Input:  grantsArray = [2, 100, 50, 120, 1000], newBudget = 190

If I pick for cap the 100 value the array becomes like this

Input:  grantsArray = [2, 100, 50, 1, 37], newBudget = 190

Now only 2 recipients affected (of course the sum of the array elements meets the newBudget constraint), but it's totally unfair.


Distributing the internal state of your queue over some globals and two arguments is an interesting decision. At least that way you can get the worst of all worlds.
enqueue assumes the queue is not full, dequeue assumes it is not empty. That's also a questionable decision.
You know that streaming a char is more efficient than streaming a length-1-string?
return 0; is implicit for main() in C++ and C99+.
I wonder why you wrap a conditional statement into its own block exactly one time. Some advocate using a block everywhere, others only where needed, but both camps are united in wanting consistency.
The inside of your first three functions somehow lost a level of indentation... and there should be a newline before main().


Your code works correctly, but can be improved (simplified and made clearer and faster).

Let't start with

func hourGlasses(input: [Int]) -> [hourglass] {
    var hourglasses = [hourglass]() // initializes hourglass to hold array of hourglass
    for index in 0..<22 { // there are 36 indexes (6x6) but we +14 in the loop below when creating the hourglass so we only need to go up to 24. We can't make hourglass with 23 and 24, so we go up to 22
        guard [4,5,10,11,16,17].indexOf(index) == nil else {continue} // continue to next iteration

        // ...
}

There are far too many magic numbers.
The fact that extened comments are necessary  indicates that the approach
it be too complicated.
I would consider this usage of guard a bit artificial.
Membership in a collection can be checked with contains(), you don't need the
actual index.

How would you extend this to 15x20 arrays? – Better iterate
over the permitted rows and columns:

for row in 0 ..< 4 {
    for col in 0 ..< 4 {
        index = row * 4 + col
        // ...
    }
}

Even better, replace the integer literals by descriptive constants:

let numRows = 6
let numCols = 6

for row in 0 ..< numRows - 2 {
    for col in 0 ..< numCols - 2 {
        let index = row * numCols + col
        // ...
    }
}

Your hourGlasses() function computes an array of arrays. Then in maxHourglassSum(),
the sum of each inner array is computed and the maximal element determined.

It is more effective to sum the values of an "hour glass" immediately instead of
storing it as an array. To compute the maximum value, use the existing method maxElement().

func hourGlassSum(input: [Int], atIndex index: Int) -> Int {
    var sum = input[index] + input[index + 1] + input[index + 2]
    sum += input[index + numCols + 1]
    sum += input[index + 2*numCols] + input[index + 2*numCols + 1] + input[index + 2*numCols + 2]
    return sum
}

func maxHourglassSum(input: [Int]) -> Int {
    var values: [Int] = []
    for row in 0 ..< numRows - 2 {
        for col in 0 ..< numCols - 2 {
            let index = row * numCols + col
            values.append(hourGlassSum(input, atIndex: index))
        }
    }
    return values.maxElement()!
}

(Remark: The sum of is computed in three separate steps because otherwise the compiler
fails with an "Expression is too complex ..." error.)

This is short, clear, works with other dimentions as well, and is faster than your original code.
If even more speed is required then you can compute the maximum "on the fly" instead of storing the
values in an array first:

func maxHourglassSum(input: [Int]) -> Int {
    var maxSum = -100 // Any initial value < -9*7 = -63
    for row in 0 ..< numRows - 2 {
        for col in 0 ..< numCols - 2 {
            let index = row * numCols + col
            let sum = hourGlassSum(input, atIndex: index)
            if sum > maxSum {
                maxSum = sum
            }
        }
    }
    return maxSum
}

More suggestions: If you plan to use the code for other shapes as well
then use an array with the indices describing the shape:

let hourGlassShape = [0, 1, 2, 7, 12, 13, 14]

func hourGlassSum(input: [Int], atIndex index: Int) -> Int {
    return hourGlassShape.reduce(0) { $0 + input[index + $1] }
}

Finally: The challenge is called "2D Array", so you might want to work with
a two-dimensional (i.e. a nested) array in Swift as well:

let inputArray2D = [
    [ 1, 1, 1, 0, 0, 0 ],
    [ 0, 1, 0, 0, 0, 0 ],
    [ 1, 1, 1, 0, 0, 0 ],
    [ 0, 0, 2, 4, 4, 0 ],
    [ 0, 0, 0, 2, 0, 0 ],
    [ 0, 0, 1, 2, 4, 0 ]
]

The sum calculation for a single hourglass then becomes more intuitive:

var sum = input[row][col] + input[row][col + 1]] + input[row][col + 2]
sum += input[row + 1][col + 1]
sum += input[row + 2][col] + input[row + 2][col + 1] + input[row + 2][col + 2]

Test code:

var sum = 0
let startTime = NSDate()
for _ in 1 ... 100 {
    sum += maxHourglassSum(inputAsArray)
}
let endTime = NSDate()
print(endTime.timeIntervalSinceDate(startTime) * 1000.0, "ms")

Results (on a MacBook, compiled in Release mode):

Original code: 0.8 ms
First variation: 0.25 ms
Second variation: 0.008 ms

The values did not change significantly when using a 2D (nested) array instead of a
1D (simple) array.


Java parsing and extract String from pattern String

There's a simpler way:

Pattern p = Pattern.compile("\\w+@\\{(\\w+)\\}");
Matcher m = p.matcher(targetStr);
while (m.find()) {
    parsed.add(m.group(1));
}

Instead of matching the opening and closing braces separately, the above pattern matches a whole expression of the form aaa@{bbb} at once. And when it finds the expression, it remembers the part inside the braces. This is done via a capturing group (the parentheses).

To learn more about each of the characters in the pattern, read the Javadoc of the Pattern class.


1. Add even more typing
It's good that you use some basic type annotations but you should use them everywhere, not just on a few select parameters. Have a look at the typing module, especially if you want to support Python versions before 3.9. For example, your function signatures could be
def __init__(self, length: int, characters: Optional[str] = None):
def generate(self, num_of_passwords: int) -> None:
def __init__(self, length: int, string_method: Literal["upper", "lower", "both"], numbers: bool = True, special_chars: bool = False):

2. Keyword-only parameters
This is a personal suggestion and I am sure you will find people who disagree with me on it. In your current code, Complex(5, "lower", True, False) is a valid call; yet, it is completely meaningless to a reader. By making the last two parameters keyword-only, you force the user to be more expressive: Complex(5, "lower", numbers=True, special_chars=False).
On that note, I suggest to give the parameters more expressive names such as include_numbers and include_special_characters.
3. Add better docstrings
You should ask yourself: who do you write your code documentation for? Right now, comments like "A simple password" don't provide much helpful information to anyone except for maybe yourself. What makes a password "simple"? Does it only contain numbers and letters? Is it short? Is it easy to remember? The same holds true for "complex", "memorable" and other terms. I'll do a shameless plug of my own recent blog post on that topic for more information.
4. Security
In the context of "passwords", "security" should always be mentioned, even if you feel that for your particular purpose you don't actually need it. Toby Speight already commented that getting words from a dictionary in the web with a hardcoded URL gives a pretty good target for attackers. An easy and platform-independent workaround would be to include a complete word dictionary in your package itself so there is no need to get it via HTTP.
Another issue might come up due to the fact that random, which you use to build your passwords, is not cryptographically secure. The secrets module, which you also used, is already a better alternative.
5. Enums
This point, again, might be a bit controversial. Instead of using "method" strings, "upper", "lower", and "both", I'd suggest to use an enum class instead, which makes it easier for your IDE to help you and gives you errors more quickly should you try to use a value that does not exist.
class PasswordGenerationStrategy(enum.Enum):
  Upper = "upper"
  Lower = "lower"
  Both = "both"