Squares with different background colors

The output of generateMaze always will be the same each time, except for one thing, which is the backgroundColor property value of the Square component.
In this case, you don't need a function/method, which output is a maze component; you can create a method to handle the maze colors, dependent on the given parameter, e.g.:
class MainMaze extends Component {
  handleMazeColor(mazeID) {
    if (mazeID === 2) return "blue";
    else if (mazeID === 3) return "red";

    return "green";
  }

  render() {
    const { tiles } = this.props.grid;
    const { grid, position, status } = this.props;

    return (
      <View>
        <CardSection>
          <Text>{grid.cols}</Text>
        </CardSection>
        <CardSection>
          {tiles.map((sq, i) => (
            <Square
              key={i}
              style={{ backgroundColor: this.handleMazeColor(sq) }}
            >
              {sq}
            </Square>
          ))}
        </CardSection>
      </View>
    );
  }
}


1. Review

The docstring doesn't explain what the function does, or how to call it, or what it returns. There's just a doctest.
If the code were reformatted to fit in 79 columns, as recommended by the Python style guide (PEP8), then we wouldn't have to scroll it horizontally to read it here at Code Review.
hexlify and unhexlify are only used by the doctest, so they could be included there.
sys is not used, so the import could be omitted.
The key derivation function is called PBKDF2, so I think the function would be better named pbkdf2, not pbkdf_two.
I don't think that having default values for arguments to this function is a good idea. The caller needs to think about these values, not rely on the defaults. Note that RFC 2898 doesn't specify any particular values.
We're not running out of letters, so why not password instead of passwd and digest_size instead of dgsz?
The helper function pbhelper is called from only one place in the code, so there's nothing to be gained by making it into a local function.
The fourth argument to pbhelper is named blocksize, but this is very misleading: it's actually the (1-based) index of the block.
The iteration variable j is not used in the body of the loop. It's conventional to name such a variable _.
Since j is not used, it doesn't matter what values it takes, and so it's simpler to use range(iters-1) instead of range(2, iters+1).
Since h is always the same, there's no need for it to be a parameter to the prf function.
The msg argument to hmac.new defaults to None so there's no need to specify it.
If the code used bytearray instead of bytes then it would be portable between Python 2 and 3 without needing a version test.
Instead of:

L = int(keylen/dgsz) # L - number of output blocks to produce
if keylen % dgsz != 0: L += 1

the number of blocks can be computed like this, using the floor division operator //:

L = (keylen + dgsz - 1) // dgsz

But even more simply, why not just iterate until the result is long enough? That way you wouldn't have to compute digest_size, and it would have the advantage that in Python 3.4 or later, the caller could pass in the name of the digest algorithm, just as for hmac.new.

2. Revised code

import hmac
import struct

def pbkdf2(password, salt, iters, keylen, digestmod):
    """Run the PBKDF2 (Password-Based Key Derivation Function 2) algorithm
    and return the derived key. The arguments are:

    password (bytes or bytearray) -- the input password
    salt (bytes or bytearray) -- a cryptographic salt
    iters (int) -- number of iterations
    keylen (int) -- length of key to derive
    digestmod -- a cryptographic hash function: either a module
        supporting PEP 247, a hashlib constructor, or (in Python 3.4
        or later) the name of a hash function.

    For example:

    >>> import hashlib
    >>> from binascii import hexlify, unhexlify
    >>> password = b'Squeamish Ossifrage'
    >>> salt = unhexlify(b'1234567878563412')
    >>> hexlify(pbkdf2(password, salt, 500, 16, hashlib.sha1))
    b'9e8f1072bdf5ef042bd988c7da83e43b'

    """
    h = hmac.new(password, digestmod=digestmod)
    def prf(data):
        hm = h.copy()
        hm.update(data)
        return bytearray(hm.digest())

    key = bytearray()
    i = 1
    while len(key) < keylen:
        T = U = prf(salt + struct.pack('>i', i))
        for _ in range(iters - 1):
            U = prf(U)
            T = bytearray(x ^ y for x, y in zip(T, U))
        key += T
        i += 1

    return key[:keylen]


Read through a log file to find serial numbers based upon prior information found

This looks like a very complex class to me. All you really want to do is read all lines of an error log and keep a dictionary mapping hardware busses to drives, where each drive has a name (like sda), a bus and a serial. If you encounter an xfs error for one of these drives, return its serial number.

This can be accomplished by defining a basically empty Drive class and filling it successively. You don't even need the SerialNumberFinder class, one function is enough:

import collections

class Drive:
    """Object to hold all information about a drive."""
    pass

def get_serial_numbers(file_name):
    """Return a list of serial numbers of drives with XFS errors"""
    drives = collections.defaultdict(Drive)
    try:
        with open(file_name) as f:
            for line in f:
                bus = re.match(r"(sd \S+) (\[sd[a-z]\]).*", line)
                if bus:
                    bus_name, device_name = bus.groups()
                    drives[bus_name].name = device_name
                    continue

                serial = re.match(r"(sd \S+) \(SERIAL=([^)]*)\)", line)
                if serial:
                    bus_name, serial = serial.groups()
                    drives[bus_name].serial = serial
                    continue

                error_disk = re.match(r"XFS ERROR (\[sd[a-z]\])", line)
                if error_disk:
                    device_name, = error_disk.groups()
                    for drive in drives.values():
                        if drive.name == device_name:
                            yield drive.serial
    except FileNotFoundError:
        print("Cannot find file {}".format(file_name))
        raise

if __name__ == "__main__":
    nums = get_serial_numbers("EXAMPLE_LOG.log")
    print(list(nums))

Note that it is often recommended to compile your regexes, i.e do something like:

bus_re = re.compile(r"(sd \S+) (\[sd[a-z]\]).*")
...
bus = bus_re.match(line)

However, Python already does this for you in the background. So whenever a new regex is encountered, it is compiled and this compiled regex is used for all future appearances of this regex. The only time when you should do this is, if you have more than 100 regexes (the default cache size), if you want to take the performance hit of compiling it once way before you run the actual code or if you want to give a regex a nice understandable name.


Calculate cumulative salary including raises

As others have noted, you'll probably want to do some error-checking on your inputs, which means writing a helper function to handle your prompts.
You're writing a program that handles money and using binary floats, which are designed for scientific calculations. You are likely to run into a variety of small calculation errors! Python has a decimal module for calculations involving money. This will also make your input-handling easier.
Don't reuse "years" as the iterator in the for loop when you already have a variable with that name. It works here, but only by luck.
Prefer the format() method to straight concatenation. In this case it allows you to easily print your numbers with comma separators.

For example:

from decimal import *

def get_decimal(prompt):
    while True:
        try:
            answer = Decimal(input(prompt + " "))
            return answer
        except InvalidOperation:
            print("Please input a number!")

def money():
    current_salary = get_decimal("What is your current salary?")
    years = int(get_decimal("How many years would you like to look ahead?"))
    percent_raise = get_decimal("What is the average percentage raise you think you will get?") * Decimal("0.01")
    for year in range(1, years+1):
        current_salary += percent_raise * current_salary
        line = "Looks like you will be making ${0:,.2f} in {1} years.".format(current_salary, year)
        print(line)


Finding number of primes till n - Sieve of Eratosthenes

You speed problem was caused by using the wrong data structure.  Since the sieve holds all the numbers up to n an Array is more efficient than a Set.

As for style I removed your subroutines and added comments.  This will improve speed with little if any lose of readability.

def primes_till n
  possible_primes = Array.new(n+1)

  (2..n).each do |n|
    possible_primes[n] = n
  end

  # numbers with multiples less than n
  (2..(Math.sqrt(n)).ceil).each do |i|
    if possible_primes[i]
      # remove all multiples of the prime
      (i**2..n).step(i).each do |x|
        possible_primes[x] = nil
      end
    end
  end

  possible_primes.compact
end

require 'prime'
require 'benchmark'
s = 100000
x =  Prime::EratosthenesGenerator.new.first(s).last
raise unless Prime::EratosthenesGenerator.new.first(s).count == primes_till(x).to_a.count

puts Benchmark.measure { primes_till(x).count }
puts Benchmark.measure { Prime::EratosthenesGenerator.new.first(s).count }

This is slightly faster than the Prime::EratosthenesGenerator, but it does not knows that maximum size of the sieve and must do some extra work to handle that fact.


internal links b/w sheets of merged workbooks, using VBA (EXCEL MACROS)

Here are a couple of pointers:

FolderPath should be a constant because it's value will never change
Using a wildcard Filter with the path will ensure that you open the correct files
Although ActiveWorkbook does the job, it is best to get in the habit of using qualified references
Workbook.Worksheets returns a Worksheets Collection (not to be confused with a normal VBA Collection)
Worksheets can be used to perform group operations on all of it's Worksheets at one time
Download RubberDuck.  Among its many great features is Code Indentation.  It will save you a ton of time reformatting and show you unclosed code blocks

Sub merge()
    Const FolderPath As String = "C:\Users\Samiya jabbar\Desktop\test"
    Const Pattern As String = "*.xl*"

    Dim Filename As String

    Dim Sheet As Worksheet

    Application.ScreenUpdating = False

    Filename = Dir(FolderPath & Pattern)

    Do While Filename <> ""

        Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True).Worksheets.Move After:=ThisWorkbook.Sheets(1)

        Filename = Dir()

    Loop

    Application.ScreenUpdating = True

End Sub


Genetic algorithm fitness function for scheduling

I think the biggest boost to readability will come from giving things proper names. You currently have a lot of RHS[r][i] going on, with i = 0, 1, 2, 3. For someone who does not know what these things are (including possibly you in a few months), this makes the code basically unreadable.

I would start by making the iteration look like this:

for r, (a, b, c, d) in enumerate(RHS):
    ...

Where a, b, c, d are actual sensible names (like name, length, or whatever is actually at those positions).

Next, your setup code can be simplified using the fact that e.g. [0] * 3 == [0, 0, 0] (but don't do it with nested loops, see below):

machine_assigne_time = [[0] * op] for op in mc_op]
max_c = [0] * len(lot_size)  # Equal number of job
completion_time = [0] * len(RHS)

And finally, without being able to run your code, the most obvious case for the slow down are your repeated calls to list.index. This is very slow (\$\mathcal{O}(n)\$ in the worst case). I would try to find a more efficient data structure for this (dictionaries?).


Here's a problem:

var o = new Observable<Unit>();
var a = o.Subscribe(_ => Console.WriteLine("A"));
var b = o.Subscribe(_ => Console.WriteLine("B"));
a.Dispose();
o.Notify(Unit.Default);

This prints

A

Disposing of a removed the wrong observer.

I'd recommend reading Why shouldn't I implement IObservable<T>?

  The reason you shouldn't implement IObservable<T> is the same reason
  you don't usually implement IEnumerable<T>, is that somebody has most
  likely already built the thing you want.


Plot on a 2D grid a spherically symmetric function

No need to iterate if the function works with arrays, and you use broadcasting to populate a grid:

def fn(X,Y):
    r = np.sqrt(X**2+Y**2)
    return 1/r**2
fn(grid_x[:,None], grid_y[None,:])

np.meshgrid and np.mgrid (or np.ogrid) can also be used to form the X,Y grid.

fn(*np.meshgrid(grid_x, grid_y))
fn(*np.ogrid[-Grid_side:Grid_side:N_pix*1j, -Grid_side:Grid_side:N_pix*1j])

Look up their docs, and practice.  Practice with simple things like grid_x[:,None]+grid_y as well.


Memory management with password retrieval

I'm not sure it's exactly insecure, but I'd consider it excessively verbose and repetitive. Given that your user, host and pass are all small, fixed-size, and allocated for the duration of a single function, dynamic allocation seems to gain little (and cost quite a bit of verbosity) with them. I think I'd write something like this:

void getprompt(char *string, size_t max, char const *prompt) {
    char buffer[16];

    sprintf(buffer, "%%%ds", max-1);
    printf("%s", prompt);
    if (scanf(buffer, string) == EOF) {
        printf("\nErrore, impossibile leggere i dati\n");
        exit(EXIT_FAILURE);
    }
}

int main(){
    char host[64], user[64], pass[64];

    getprompt(host, sizeof(host), "--> Inserisci hostname (max 64 caratteri): ");
    getprompt(user, sizeof(user), "\n--> Inserisci username (max 64 caratteri): ");

    printf("\n--> Inserisci password (max 64 caratteri): ");
    get_pass(&host,&user,&pass);

    /* Stampo a video le informazioni immesse */
    printf("\n\nHost: %s\nUser: %s\nPass: %s\n\n", host,user,pass);

    return EXIT_SUCCESS;
}

There also seems to be no reason to pass host or user to get_pass -- it doesn't really use them (and logically, shouldn't). I'd probably write it as a wrapper around getprompt -- do the tcsetattr, call getprompt, then undo the tcsetattr. Although you have matched the sizes correctly in this case, your get_pass has implicit knowledge of the size of pass; it works as-is, but is relatively fragile, so in the long term it would be fairly easy for somebody to create a hole by adjusting the size in get_pass but not in main (or vice versa).

I'd also consider changing getprompt to return a bool indicating success/failure rather than having it directly exit the program. Along with the suggested change to getpass, that would turn your main into something like:

int main() {
    char host[64], user[64], pass[64];

    if (getprompt(host /* ... */) &&
        getprompt(user /* ... */) &&
        get_pass(pass /* ... */)
    {
        printf("\n\nHost: %s\nUser: %s\nPass: %s\n\n", host, user, pass);
    }
    return EXIT_SUCCESS;
};

Bottom line: I don't see any obvious security holes in the code as it stands, but it strikes me as excessively verbose and rather fragile. It's unnecessarily difficult to be certain that it's correct now, and likely to get broken in the long term even if it is all correct now.


Clumsy PHP5 code reading from an SQLite3 database

You are right, the foreaches can be eliminated.  The first foreach which grabs the highest id, can be eliminated by taking advantage of the fact that the query will only ever return a single cell and using the PDOStatement::fetchColumn() method.  Since page ids are unique, the second foreach can be removed because the second query will only ever return a single row.

An additional problem is that you are not sanitizing user input in your SQL.  This is easy to fix with PDO by using a parameterized statement:

<?php
// Open the database.
$db = new PDO("sqlite:pagesdatabase.db");

// Is id set? If not get id of last page and put it in $id.
if (!isset($_GET["id"])) {
    $id = $db->query("select max(id) from pages")->fetchColumn();
}
// If id is set, get the value and put it in $id.
else {
    $id = $_GET['id'];
}

// You may consider doing an additional check here in case there are no pages, in which
// case id will be null
if ($id === null) {
    // ...
    exit;
}

// Using the id number, grab the title, body, time and timezone of post.
$page = $db->prepare("select * from pages where id = :id")
           ->execute(array('id' => $id))
           ->fetch();

// A check for an invalid id should be made here
if ($page === null) {
    // ...
    exit;
}

$title = $page['title'];
$body = $page['body'];
$time = $page['time'];
date_default_timezone_set($page['timezone']);
?>

I have only quickly prepared this answer from experience and have not actually run the code above.  It should be enough to give you an idea but may have syntax errors.  If it does, comment on the post and I will fix it.  Also, if reducing this code to the fewest lines possible is your goal, setting $id can be accomplished with a ternary and the actual retrieval of the page along with the error checks can be encapsulated in a function or a class.

<?php
// Open the database.
$db = new PDO("sqlite:pagesdatabase.db");

// Determine if a page id is provided, if not use the most recent page
$id = isset($_GET['id'])
  ? $_GET['id']
  : $db->query("select max(id) from pages")->fetchColumn();

try {
    $page = Page::fetch($id, $db);

    $title = $page->getTitle();
    $body = $page->getBody();
    $time = $page->getTime();
    date_default_timezone_set($page->getTimezone());

} catch (Exception $e) {
    // This exception should be thrown by Page::fetch if no pages exist or an invalid
    // id is given
    // ...
    exit;
}
?>

If this is preferred I will leave the class definition to you.


PowerShell script creates a computer list from an AD OU, and add exclusions to a specific file via Invoke-Command

Your try block will be unable to pass the error to catch block if you don't use -ErrorAction Stop. Also there is an -ErrorAction Ignore on powershell v3.0+ that completely ignores the error.


I would slightly change this code:

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    // Args arrangement
    let mut args = std::env::args().skip(1);
    assert_eq!(args.len(), 3, "Arguments must be: file_location width height");

    // Reading args
    let file_location = args.next().unwrap();
    let width = args.next().unwrap().parse()?;
    let height = args.next().unwrap().parse()?;

    // Do the job
    let img = image::open(&file_location)?;
    img.thumbnail(width, height);

    // All was ok
    Ok(())
}

You can take advantage of the try operator ? to make the error handling easier.
Similarly, you can add a bit of error handling with the assert_eq line. You can use the len method because this iterator knows exactly how much elements it has.
You can use skip to discard the first element of the Args iterator.


Pulling JSON using jQuery and manipulating the Front-end

Functions in JavaScript, by convention, begin with a lowercase letter, unless they're constuctors. So Details() should be details()

You've got some missing indentation, which makes the code harder to read. In general your code could probably benefit from a bit more whitespace to help legibility.

You also have some funky-looking strings, like: '<input type=\"hidden\" name=\"productCodePost\" value=\"'
You use single quotes around the string, but still escape the double-quotes inside the string. This is unnecessary: A single-quoted string can contain double-quotes just fine, and a double-quoted string can contain single-quotes (like so 'double-quotes (") work fine here' or "single-quotes (') work fine here"). You only need to escape if your string contains the same type of quote that you're using to delimit the string.
In fact, you're already doing that in your code. The rest of the line I used as example looks like this '\"><input type="submit" value="Out">' and works just fine with out any backslashes.

You can also use jQuery to build those elements for you, i.e.

form.append($("<input>").attr({
  type:  hidden,
  name:  productCodePost,
  value: sku
});

which gives you a more structured and readable source code, instead of giant strings.

There's also a lot of repetition - or semi-repetition in this case: The el+"...". I'd advice something like what Matt suggested which is to store the result of $(el) once, and from there using .find() to locate the individual elements you want to update.

For the actual element updating there isn't that much that can be improved, since there's no discernible commonalities between, say, element IDs and JSON keys (in fact, the JSON seems very messy!)

There are some minor things you could do like define a renderAmount function to make sure you're always printing prices the same way:

function renderAmount(amount) {
  return "£" + Number(amount).toFixed(2);
}

Right now, you only use the .toFixed() in one place, although you have 3 different places where you need to write amounts.

Similarly, you could add a function to update images, since you do it at least twice. Not a great savings, but it helps break up the code.

function updateImage(element, info) {
  element.attr({
    src: json.url,
    alt: json.altText
  });
}

// ...

updateImage(container.find(".p_img img"), json.images[2]);

Lastly, what's going on the element that shows the savings? If there's no old price, it's just hidden, which makes sense. But if there is an old price, you update the .p_save element... and then hide it anyway?


Use built-ins
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

This is a very verbose and error-prone way of getting all of the ASCII lowercase letters.
from string import ascii_lowercase as alpha

will give approximately the same result.  It is a string, instead of a list, but Python strings are effectively just lists of characters.  In particular, alpha[0] will be 'a' and alpha[25] will be 'z'.
Unnecessary str()
The result of a ''.join(...) call will be a string.  Wrapping this in a str(...) call is pointless.
Unnecessary abs()
for j in range(0, n-1) means that j will always be less than n-1.  In other words:
$$ j \le n - 2 $$
Consider, abs(n-(j+2)):
$$ j \le n - 2$$
$$ j + 2 \le n$$
$$ n - (j+2) \ge 0$$
In other words, the abs(...) is unnecessary, and just adds confusion.
General Comments
Follow PEP-8 guidelines (spaces around operators, etc).  Use functions.  Use a main-guard.
Reworked & Simplified Code
from string import ascii_lowercase

def print_rangoli(n: int) -> None:

    alpha = ascii_lowercase[:n]

    for row in range(- n + 1, n):
        row = abs(row)
        dashes = "-" * (2 * row)
        print(dashes + "-".join(alpha[:row:-1] + alpha[row:]) + dashes)

if __name__ == '__main__':
    n = int(input("Enter a size: "))
    print_rangoli(n)

Format Specification Mini-Language
Python's format statement (and f-strings) use a format specification mini-language.  This allow you substitute values into a larger string in fixed-width fields, with your choice of alignment and fill characters.  Here, you'd want centre alignment, with '-' for the fill character.
For example, f"{'Hello':-^11}" is a f-string, which places the string 'Hello' into a field 11 characters wide, centre justified (^), with '-' used as a fill character.  Producing '---Hello---'.  Instead of a hard-coded width (11 in the above example), we can use a computed {width} argument.
Using this, we can further "simplify" (for some definition of simplify) the print_rangoli function:
def print_rangoli(n: int) -> None:

    width = n * 4 - 3
    alpha = ascii_lowercase[:n]

    for row in range(- n + 1, n):
        row = abs(row)
        print(f"{'-'.join(alpha[:row:-1] + alpha[row:]):-^{width}}")


LeetCode: Greatest Common Divisor of Strings C#

The first step in your method is to determine the longest common prefix. Here it would be sufficient to determine the length of the longest common prefix. Building the prefix string itself is not necessary at this point.

The next step is to decrease that length until it divides both string lengths. An explaining comment would be helpful here. We still don't need the prefix string itself, it suffices to decrease the previously determined prefix length.

Finally you determine if the prefix “divides” both strings. At this point we can build the actual prefix string. Again a short comment could be helpful. Instead of the inner loop I would compare substrings (unless that turns out to be too slow):

var prefix = str1.Substring(0, prefixLength);

// Verify that `str1` is a multiple of `prefix`:
for (int i = 1; i < str1.Length / prefixLength; i++)
{
    if (prefix != str1.Substring(i * prefixLength, prefixLength))
    {
        return string.Empty;
    }
}

// Same for `str2` ...

Note that the loop can start with i = 1 because we already now that both strings start with prefix. Since the same logic is applied to both strings I would also consider to move it to a separate IsMultipleOf function.

Performance: Consider the following example:

str1 = "AAA......A"  //  999 characters
str2 = "AAA......AA" // 1000 characters

Your method builds a prefix string of 999 characters first, and then removes successively all but one character, because 1 is the only length that divides both string lengths.

As mentioned above, this can be improved by updating the prefix length only, but one can still do better:

It is not difficult to see that the length of X must be exactly the greatest common divisor of the lengths of str1 and str2 – and that can be determined efficiently with the Euclidean algorithm.

The implementation would then look like this:

private static int gcd(int a, int b)
{
    // Your favorite implementation of the Euclidean algorithm...
}

public static string GcdOfStrings(string str1, string str2)
{
    var prefixLength = gcd(str1.Length, str2.Length);
    var prefix = str1.Substring(0, prefixLength);

    // Is it a common prefix?
    if (prefix != str2.Substring(0, prefixLength)) {
        return "";
    }

    // Verify that `str1` is a multiple of `prefix` ...
    // Verify that `str2` is a multiple of `prefix` ...

    return prefix;
}


The problems I see here involve code duplication and magic values, and perhaps some incomplete logic.

You use the numbers 120, 471, 353. I don't know what those mean. And they're duplicated. Make those variables with descriptive names.

Now let's look at this:

//if Landscape
if (width > height && width >= 471)

This is more than than just if landscape. This is if landscape and is too big. But I'm not encouraging you to write a better comment! Instead, I encourage you to encapsulate that conditional into it's own method, with a more descriptive name, and then remove the comment.

private bool IsLandscapeAndTooBig(width, height)
{
    return width > height && width > maximumWidth; // notice the new variable?
}

The same idea applies to your "if portrait" piece.

Let's look inside those ifs now. Again, the problem is the magic values, but perhaps these inner blocks need to be methods, perhaps ResizeLandscape and ResizePortrait (but you probably want to think a bit longer on these names). And instead of operating on 4 local variables, perhaps they should instead return a single encapsuting data object.

class ImageDimension
{
     public int ThumbWidth { get; set; }
     // continues
}

one other thing I see is that you build thumbnail dimensions for too large of a landscape and too large of a portrait, but you don't seem to build them for images that are not too large. Does something just smaller than your threshold for "large" not need a thumbnail? This is where I think you might have some missing logic. On the other hand, you might not, I don't know entirely what you are trying to do. Just keep this in mind.


Indentation:

You're missing indentation in your code, you should space out each level of indentation.

For example:

for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
    output += "fizz";

would become:

for (var n = 1; n <= 100; n++) {
    var output = "";
    if (n % 3 == 0)
        output += "fizz";

Use braces

You should wrap your code in braces, so you don't cause any bugs unknowingly:

For example, you (or someone in future that maintains your code) might think this wouldn't log anything, however, "omg" is logged.

if (5 != 5)
    console.log("wow");
    console.log("omg")

Even Apple got caught out by one of these bugs.

Unnecessary logic:

In your block, you check whether the number is divisible by 3, then by 5, then by 3 and 5. You don't need to perform the last check of 3 and 5, the first two make up that one.

Leaving you with:

Implementing all those changes, you would end up with:

for (var n = 1; n <= 100; n++) {
    var output = "";
    if (n % 3 == 0){
        output += "fizz";
    }
    if (n % 5 == 0){
        output += "buzz";
    }
    console.log(output || n);
};


There is no requirement to report the characters in any particular order. As a result, there's some tricks we can do to improve the performance.

Other tricks to use are:

work using primitive char[] arrays instead of Strings.
use better variable names

Sorting the data is a good first step:

    char[] expect = bi.readLine().toCharArray();
    char[] search = bi.readLine().toCharArray();

Now we sort them both:

Arrays.sort(expect);
Arrays.sort(search);

Then, we loop through the search values, and look for characters that do not appear in expect:

StringBuilder usedCharacters = new StringBuilder();
int searchPos = 0;
while (searchPos < search.length) {
    int expectPos = Arrays.binarySearch(expect, search[searchPos]);
    if (expectPos < 0) {
        usedCharacters.append(search[searchPos]);
    }
    // advance to the next character, may be duplicates.
    searchPos++;
    while (searchPos < search.length && search[searchPos - 1] == search[searchPos]) {
        searchPos++;
    }
}

return usedCharacters.toString();

Now, how will this relate in terms of performance?

Your current code loops through each search character, which is an \$O(n)\$ operation. For each character, it then does a search through previously searched characters, and also the unsearched characters. The combination of these two loops leads to a \$O(nm)\$ operation.

In contrast, the sorts on the input data are \$O(n \log{n})\$, and \$O(m \log{m})\$ and the subsequent searches are \$O(n \log{m})\$

The end result will be much more favourable than \$O(nm)\$


Elixir/Ecto find_or_create with custom error

I think it is a perfect fit for with. It will be something like:

def find_or_create_user(attrs \\ %{}) do
  with  true <- String.ends_with?(attrs.email, "@test.com"),
        nil <- Repo.get_by(User, %{email: attrs.email}),
        {:ok, user} <- create_user(attrs)
  do
    {:ok, user}
  else
    false -> {:error, :invalid_email_domain}
    %User{} = user -> {:ok, user}
    {:error, changeset} -> {:error, changeset}
    _anything_else -> {:error, "cannot find or create user"}
  end
end


First you should clean up your code - add whitespace, remove unnecessary comments, don't use semicolons, store repeated computations in variables, move repeated code fragments into functions, etc.

Second, if at all possible give them more descriptive names - I have no idea what this is about.  A good way to do this is to figure out the different sections (you have them labelled with comments) and then turn each section into a well-named, small function. This way you can clearly document what each section does and why, without having to add comments that clutter everything up. Prefer expressing yourself in code over in comments whenever possible.  Some people even consider writing comments a shameful act - I don't personally go that far, but here are some good articles about it:

https://blog.codinghorror.com/coding-without-comments/
https://visualstudiomagazine.com/articles/2013/06/01/roc-rocks.aspx

Robert C Martin talks a lot about this - I'd highly recommend reading his work.

  Comments are, at best, a necessary evil, nothing to celebrate
  The proper use of comments is to compensate for our failure
  to express ourself through the code itself
  http://www.cvc.uab.es/shared/teach/a21291/temes/coding_style/slides/comments.pdf

Third, use the right data structure for the job. Anytime you have name-value pairs and you aren't using a dictionary you're probably doing something wrong.  Whenever you have a list but you never mutate it, you should make it a tuple.

Fourth, if you use the start keyword argument to enumerate you can get rid of a lot of extra code. You can then compress your data curves section pretty easily.

Once you've moved things into some nice clean functions, you can then put your runtime code into an if __name__ == '__main__' block.

Last, I'd make a wrapper that turns your workbook into a context manager. This way you can make sure that the workbook is saved, and it makes things quite a bit cleaner.

You might also want to consider adding support for command line arguments, making it easier to generate a lot of sheets like this that operate on different parameters.

I ended up with something like this

import numpy as np
import xlwt
import contextlib

def write_to_sheet(sheet, row, column, name, value):
    sheet.write(row, column, name)
    sheet.write(row, column + 1, value)

def write_variables(sheet, variables):
    write_dict(sheet, 0, variables)

def write_conditions(sheet, column, conditions):
    write_dict(sheet, column, conditions)

def write_dict(sheet, column, dict_):
    for row, (name, value) in enumerate(dict_.items()):
        write_to_sheet(sheet, row, column, name, value)

def write_data_curve(sheet, data_curve, start_row, start_column):
    for column, (header, data) in enumerate(data_curve.items(), start=start_column):
        sheet.write(start_row, column, header)
        for row, value in enumerate(data, start=start_row + 1):
            sheet.write(row, column, value)

def write_data_curves(sheet, amin, amax, da):
    t2 = np.arange(0.0, 5.0, 1)
    amat = np.arange(amin, amax, da)
    col = 3

    for a, fn in ((a, a * t2) for a in amat):
        conditions = {
            'eps_dot': a * 1.,
            'Delta_t': a * 1.
        }
        write_conditions(sheet, col, conditions)

        data_curve = {'strain': fn, 'stress': t2,
                      'd11s': fn, 'd_dot': t2,
                      'd11': fn}
        write_data_curve(sheet, data_curve, len(conditions) + 1, col)

        col += 6

@contextlib.contextmanager
def open_book(filename):
    workbook = xlwt.Workbook()
    yield workbook
    workbook.save(filename)

if __name__ == '__main__':
    amin = 2
    amax = 10
    da = 2

    variables = {
        'amin': amin,
        'amax': amax,
        'da': da
    }

    with open_book('EXPORTexample.xls') as book:
        sh = book.add_sheet('sheet 1')
        write_variables(sh, variables)
        write_data_curves(sh, amin, amax, da))


The problem is here: collect { |v| (v - mean) / standard_deviation }. standard_deviation is constant but, being inside a block, it is called on each iteration. Set the value to a local variable before. As noted by Flambino, the same principle applies to sample_variance (which uses mean inside a block).

In a functional language (where immutability is honored) the compiler would be able to do the right thing, but not in an imperative language plagued with side-effects like Ruby.

Some additional notes to your code:

module Enumerable: But you call .length, which is not a method that an enumerable is required to implement. Consider adding them to Array (which includes Enumerable).
reduce and then inject. I'd use just one of the alias.


Program to count the number of lines of code

First a small nitpick: in python the prevailing naming convention for function names is all lowercase, with words separated by underscores. So CountFile should be count_file, or even better would be something like count_lines, since count_file doesn't really explain what the function does.

Now in CountFile, you read the file using f.read() then split on newlines. This isn't really necessary -- for one thing because file objects have a method called readlines which returns a list of the lines, but more importantly because file objects are iterable, and iterating over them is equivalent to iterating over the lines. So for line in f.read().split('\n'): is equivalent to for line in f:, but the latter is better because when you call read() you actually read the entire contents of the file into memory, whereas for line in f: reads the lines one at a time. It's also the idiomatic way to go about reading a file line by line.

If you're not concerned about memory, however, then because flat is better than nested you can do away with the explicit for loop and just call len on your list of lines. The entire function could be return len(open(f, 'r').readlines()) (but this isn't really advisable in the general case because of the memory thing). You could also use a generator expression and write return sum(1 for line in f).

Now notice that in CountFile, you write f = open(f, "r") to open a file, then later you write f.close() -- this kind of pattern is what context managers and the with statement were introduced for. The context manager protocol is already conveniently implemented for file objects, so you could write:

counter = 0
with open(f, 'r') as f:
   for line in f:
       counter += 1

And you wouldn't need to explicitly close the file. This may not seem like such a big deal in this case, and it isn't really, but with statements are a convenient way to ensure you that you only use resources (like files, or database connections, or anything like that) just as long as you need to. (Also, allocating and later freeing a resource might be a lot more involved than just calling open and close on it, and you might have to worry about what happens if something goes wrong while you're using the resource (using try... finally)... Hiding that behind a with statement makes for much more readable code because you can focus on what you're trying to accomplish instead of details like that.)

Your CountDir function looks mostly okay. You might look into using os.walk instead of os.listdir so you won't need to check for directories -- it would look something like

for root, _, files in os.walk(dirname):
    for f in files:
        count += CountFile(os.path.join(root, f))

(The _ doesn't have any special meaning, it just by convention means that we won't be using that variable.) Another advantage of os.walk is that by default it doesn't follow symlinks, whereas listdir doesn't care, so if you don't explicitly check for symlinks you might end up counting things twice.

If you stick with os.listdir, you could still make your code a bit cleaner by using a conditional expression, which would look like:

counter += CountDir(fa) if os.path.isdir(fa) else CountFile(fa)


Multi threaded Producer Consumer with bounded buffer

Suggest adding final to the QUEUE_SIZE constant and the collection instance also.

synchronized usage for protecting the ArrayDeque collection from concurrent access, but ArrayDeque is not thread safe. Perhaps two threads, one calls getWork() and another the addWorkItem(Integer i). Suggest using a thread safe collection instead of ArrayDeque.

Multiple threads may not always have access to System.out. Instead can use a concurrent logger or other mechanism to capture output, or have each thread write to a thread safe collection as an instance in ConsumerProducer1. Another option is having a Callable that returns desired output as a String, with the main routine the only thread accessing System.out and echoing that result.


Advice 1

array.shrink_to_fit();: don't do it. If the implementation obeys strictly that request, you will waste a lot CPU cycles.

Advice 2

Whenever you publish your results, make sure that your algorithms/data structures do not write to standard output.

Advice 3

You can micro-optimize your max_heapify. Instead of swapping \$n\$ times, do a shift (see image below). When you have to swap, you sacrifice 3 assignments, so the total work is \$3n\$. If you do a shift instead, you make \$n + 1\$ assignments.

Advice 4

T heap_extract_max(std::vector<T>& array)
{
  if(array.size() < 0)
  {
    std::cerr << "Heap Underflow \n";
    return -1;
  }

I believe bad things will happen when T is not an integer.


Welcome to CodeReview! Your general structure is already pretty good and the comments made the code easy to read. Here are some key suggestions and explanations. The full code can be found at the bottom.

Comments
Comments should generally not (have to) explain every single line, especially really simple lines like an import:
# This imports the random function
import random

Any Python developer that reads this will know what the line does. Adding a comment here significantly increases the time needed to read and understand the code, so I'd advise against simple comments like this.

f-Strings
f-Strings offer a convenient and readable way to print text that includes variables:
print("You have " + tries + " tries left.")

becomes
print(f"You have {tries} tries left.")

dashes and update_dashes
Since you need to modify dashes multiple times I would suggest a mutable data type instead of a str, e.g. a list.
dashes = ["-"] * len(secret_word)

Since it's now a list, we would need to print it by calling "".join(dashes). We'll put that in its own seperate __str__ function in the next point.
This allows for a more concise definition of update_dashes(...):
def update_dashes(secret_word, dashes, user_guess):
    for index, letter in enumerate(secret_word):
        if letter == user_guess:
            dashes[index] = user_guess

Multiple things to notice here:

dashes is modified in-place, therefore we don't need to return it. Passing it to the function is enough.
Using enumerate will give us index and letter for all letters in secret_word. This approach is more pythonic than iterating over a range and accessing the elements by their index.
We do not immediately return once we find a matching letter. This is important because we can have multiple occurences of the same letter in secret_word.

class Dashes
I would say dashes combines enough unique logic, for it to make sense to make it a standalone-class. This comes down to some personal preference, but I find it improves the code structure here.
class Dashes:
    PLACEHOLDER = "-"

    def __init__(self, secret_word):
        self.secret_word = secret_word
        self.letters = [self.PLACEHOLDER] * len(secret_word)

    def update(self, guess):
        for index, letter in enumerate(self.secret_word):
            if letter == guess:
                self.letters[index] = guess

    def is_completed(self):
        return self.PLACEHOLDER not in self.letters

    def __str__(self):
        return "".join(self.letters)

As you can see, Dashes now handles a lot of useful logic for the rest of our program.

Complete code
Some other points worth mentioning:

You should avoid using global variables as far as possible. Global variables aren't good practice, as they can lead to some unexpected behaviour / confusing bugs.
Wrapping your program's main functionality into a main() function is generally good practice. Wrapping your call to main() into a if __name__ == '__main__': condition is also a good idea. You can read more about it here.
For if-conditions that break or continue a loop or return from a function, it often improves readability to move them into seperate conditions instead of an if ... elif ... elif ... else construct.
user_guess.islower() == False is equivalent to not user_guess.islower(), and even better user_guess.isupper().
When checking if user input is not a letter, you should use not user_guess.isalpha() instead of only checking for numbers with user_guess.isnumeric().
tries = tries - 1 is equivalent to tries -= 1.
Imports should usually be found at the top of your code file.
We only need to update dashes if the user_guess is in secret_word.
The length of secret_word will probably never be performance-critical. In general, if we need to perform multiple (performance-critical) membership tests (e.g. letter in word), sets provide lookups in constant instead of linear time.

Here's the full code without comments:
from random import choice

class Dashes:
    PLACEHOLDER = "-"

    def __init__(self, secret_word):
        self.secret_word = secret_word
        self.letters = [self.PLACEHOLDER] * len(secret_word)

    def update(self, guess):
        for index, letter in enumerate(self.secret_word):
            if letter == guess:
                self.letters[index] = guess

    def is_completed(self):
        return self.PLACEHOLDER not in self.letters

    def __str__(self):
        return "".join(self.letters)

def get_guess():
    while True:
        user_guess = input("Guess a letter: ")

        if not user_guess.isalpha():
            print("That is not a letter!")
            continue

        if len(user_guess) != 1:
            print("You can only enter one letter!")
            continue

        if user_guess.isupper():
            print("Remember to enter a lowercase letter, but I'll swap it for you this time :)")
            return user_guess.lower()

        return user_guess

def main():
    words = ["jazz", "hello", "bird", "birds", "peanut", "butter", "cake", "hallway"]
    secret_word = choice(words)

    dashes = Dashes(secret_word=secret_word)

    tries = 10

    while tries > 0 and not dashes.is_completed():
        print(dashes)
        user_guess = get_guess()

        if user_guess in secret_word:
            print("That letter is in the secret word!")
            dashes.update(user_guess)
        else:
            print("That letter is not in the secret word.")
            tries -= 1
            print(f"You have {tries} tries left.")

    if dashes.is_completed():
        print(dashes)
        print(f"You guessed correctly, the word was {secret_word}!")
        print("--------------------------YOU WIN!----------------------------")
    else:
        print(f"You ran out of guesses, the word was {secret_word}.")
        print("--------------------------YOU LOSE----------------------------")

if __name__ == "__main__":
    main()


The implementation of indexJ seems to be broken. In particular:

indexJ i (Append _ left right)
  | (getSize . size . tag) left >= i = indexJ i left
  | otherwise                        = indexJ i right

indexing with i in the right part is wrong. I'd suggest you to create a function that converts a list into a JoinedList (ideally a blanced one), and then test if indexing into the list produces the same result as indexing into the JoinedList.

Also the implementation of tag is missing, but this is a crucial part of the code, without it it can't be really reviewed.

I'd also suggest to implement other operations on JoinLists, in particular creating a singleton list and concatenation, perhaps also prepending/appending an element to a list.

Finally, you're using a Monoid instance for tagging the tree. This is in general a good idea, but the assignment doesn't say anythong about monoids, sobe sure to understand how the monoid there should be used. You never use the fact that m a monoid in your code. If you're unsure, I'd suggest to forget about monoids at this point and use just the provided Size data type.


Improving a JavaScript filtering function

You're mixing up two different ways of doing this. The old-fashioned way involves looping through the alphabet and pushing the letters not present into an array:

function getLettersNotInContent2(letters) {
    var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    var notPresent = [];
    for (var i = 0; i < alphabet.length; i++) {
        if (letters.indexOf(alphabet[i]) === -1) notPresent.push(alphabet[i]);
    }
    return notPresent;
}

The newer way (more elegant but not supported in IE8) uses the filter method with a function that returns true or false:

function getLettersNotInContent3(letters) {
    var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    return alphabet.filter(function (letter) {
        return letters.indexOf(letter) === -1
    });
}

Your code happens to work because, under the hood, filter also loops through the values of an array in turn. But you're not using it in the intended way.

(In both cases I removed the filtering out of duplicates as this seems unnecessary.) (jsfiddle)


Zip the contents of subfolders, conditionally

Path Location

I see that you're trying to save the current location and then restore it later.

There are actually built-in cmdlets for this, Push-Location and Pop-Location. They work the same way as pushd and popd if you're familiar with those from the regular Windows command prompt for from unix-like systems (and in fact those terms are aliases in PowerShell and still work).

So you can actually just do this:

Push-Location  # saves the current location
# do some stuff
Pop-Location   # restores the original location

You can also give a location to change to, so for example instead of doing Set-Location later, you can do something like this:

$dirToChangeTo = 'C:\Windows'
Push-Location $dirToChangeTo
# do stuff in the new location
Pop-Location   # original location restored

Handling Errors

There's a small problem with any of these methods though: if your script doesn't execute all the way through for any reason, your original location will not be restored. For that you can wrap your entire script in a try/finally block:

Push-Location
try {
    # all your code here
} finally {
    Pop-Location
}

The idea with this is that the code in finally {} should execute always (if a fatal exception occurs, if you stop the script, press CTRL C, etc.), so you can be fairly certain that your original location will get restored. I do this all the time when dealing with the SQLPS module because it always changes the location to the SQLPS drive.

Avoiding this altogether

Of course you really don't have to change the current location. The only place you're using it is where you're finding the zip files, but you could have just passed the current directory into the -Path or -LiteralPath parameter of Get-ChildItem and then you would avoid the need to worry about changing it. I tend to prefer this method personally.

Iterating Directories

The Pipeline

foreach($path in get-childitem -recurse) { #get all subfolders

Get-ChildItem is a pipeline cmdlet, so I would typically recommend you stay with the pipeline, as it tends to be a bit more natural in PowerShell:

Get-ChildItem -Recurse | ForEach-Object {
    $path = $_
}

Getting Directories Only

if ($path.Attributes -eq "Directory") {

You don't need to test for a directory after the call. If you're using PowerShell 3 or higher, you can just do:

Get-ChildItem -Directory -Recurse | ForEach-Object {
    $path = $_  # this will be a directory
}

If you're using v2 you can still keep it in the pipeline but it's a bit more verbose:

Get-ChildItem -Recurse | Where-Object { $_.PSIsContainer } | ForEach-Object {
    $path = $_  # this will be a directory
}

Date Formatting

$date = "$((Get-Date).ToString('yyyy-MM-dd_hh-mm'))"

There's no need to embed this in a string; calling .ToString() will already give you one!

Get-Date has a -Format parameter that takes the same format string as .ToString() so you could just do:

$date = Get-Date -Format 'yyyy-MM-dd_hh-mm'

If you prefer .net objects, you could do it without any cmdlets:

$date = [DateTime]::Now.ToString('yyyy-MM-dd_hh-mm')

12 vs 24 hour clock?

This may be culture dependent and I'm not sure where you are, but on my system 'hh-mm' will give me the 12-hour time, and you're not including AM/PM in your string.

So right now for me it's 8:14 PM and Get-Date -Format 'hh-mm' gives me 08-14. It would give me the same thing in 12 hours though. 'HH-mm' will give me 20-14 which is probably what you want to do here instead of embedding am/pm, but if you did I believe the format code is tt:

Get-Date -Format 'hh-mm tt'

Path Combining

$newpath = [io.path]::combine("$path$date","")

I'm not sure what you're doing here. This is the same thing as:

$newpath = "$path$date"

[System.IO.Path]::Combine() is a way to combine multiple path components without having to concatenate them yourself (and deal with leading/trailing path separators). Am empty string as one of the parameters effectively gets ignored.

It's a great function to know though. There is also the Join-Path cmdlet which does the same thing but in a more "PowerShell" style of course.

Aliases and Item Type

$items = Get-ChildItem -Exclude *.zip | ? {$_.LastWriteTime -lt (Get-date).AddDays(-31) -and -not $_.psIsContainer}

Aliases

? is an alias for Where-Object. Try to avoid aliases in scripts you intend to reuse, especially if they'll be shared or read by others.

Item Type

As above, if you're using PS3+ you can use Get-ChildItem -File to get only files, otherwise you're already doing the right thing with .PSIsContainer.

Test-Path already returns [bool]

if ( $(Try { Test-Path $items } Catch { $false }) ) {

There's no need to use try/catch here; Test-Path already returns $true or $false so you can just use it directly:

if (Test-Path $items) {

else { continue } is Unnecessary

That's what was going to happen anyway!

Adding Parameters

I definitely get the idea of this operating on the current directory, but it would be nice to be able to launch it from anywhere and tell it what directory to operate on. To do that, you add a param() block at the top of the script:

# very top of script, pretend this isn't here
[CmdletBinding()]
param(
    [ValidateScript( { $_ | Test-Path -Type Container } )]
    [String]
    $InitPath = (Get-Location)
)

# rest of code

Now you can call your script with -InitPath C:\some\directory or just leave it blank and it will use the current working directory anyway. And I threw in a parameter validation attribute to make sure that the passed in value exists and is actually a directory.

Parameterizing a script is something I tend to recommend a lot; it's something good to think about in general because it tends to make your code more versatile, testable, etc.


One program using three functions to compare two double-precision numbers

Your functions and their use are very curious:

A function to determine if two values are similar should be symmetric in its arguments, and return a bool.
A function determining the truth of a property should be called is@. similarValue is a bit of a puzzler, which is actually good as the functions behavior is very surprising.
A conditional expression returns a bool, which can be implicitly converted to an integer of value 0 (false) or 1 (true).
I'm not sure what I should do with valueSmaller and valueLarger, but I am sure that I don't want to see anything like them ever again.

Other points:

Seems you also don't know the conditional-operator (expr ? value-if-true : value-if-false). It can be used to write things better, but beware of getting carried away with it.
You are using using namespace std;.
That's a bad idea, read "Why is “using namespace std;” considered bad practice?".
When you output string- and char-literals consecutively, just concatenate them together. Also, if you have a length-1-string-literal, a char-literal can serve the same purpose more efficiently.
Your comments are, I'm sorry to say, useless, as they just rephrase some of the more obvious code.
When you use descriptive names, most other comments for describing what code does also become superfluous (exception: doc-comments which will be extracted for bare-bones documentation).
Comments are for giving non-obvious reasons for doing things you do, reasons for doing them the way you do them, or describing how you do something.
See this good answer by rolfl about how to properly comment.


In case you don't know, sockets in Pythons can have an associated timeout. This will take care of the setblocking(0) + select part for you. Just catch the socket.timeout exception and decide what to do when the operation was canceled.

You can also set the timeout directly as the second argument to create_connection.

You can thus read from the socket using:

def print_recv(sock):
    while True:
        try:
            msg = sock.recv(4096)
        except socket.timeout:
            pass
        else:
            sys.stdout.write(msg)
            sys.stdout.flush()

Granted that the socket already has an associated timeout (or you can call sock.settimeout(0.1) as the first instruction of the function).

As a side note, this function does not account for shutdowns of the connexion from the server. If you want to handle this case, you can detect it when recv return an empty message. So the basic thing to add could be if not msg: break before sys.stdout.write(msg).

Using this function as a thread, you can close the socket from the outside, somehow like you did in your second version, but the socket will, at some point, trigger an OSError on sock.recv. Catching that could be a bad idea, as it may hide more serious issues. Instead, I’d still rely on threading.Event:

def print_recv(sock, event):
    while not event.is_set():
        try:
            msg = sock.recv(4096)
        except socket.timeout:
            pass
        else:
            if not msg:
                break
            sys.stdout.write(msg)
            sys.stdout.flush()

So you’ll have to event.set() before socket.close() outside of the thread. Note, however, that due to scheduling randomness, the order of execution could be:

while not event.is_set(): # Thread-1
event.set()               # Main thread
sock.close()              # Main thread
    msg = sock.recv(4096) # Thread-1

and still lead to an OSError. It will not happen so often, but it will. So you may want to come up with better synchronization if you want a cleaner termination.

You’ll also note that I’m using a function instead of a method to print the messages from the server. It feels cleaner as it separate concerns. In fact, there is no real need to create a class here, appart from keeping around a bunch of related objects. But your setup + teardown logic had me wondering: this is a job for a context manager:

class NetcatManager(object):
    def __init__(self, rhost, rport):
        self._event = threading.Event()
        self._socket = socket.create_connection((rhost, rport))
        self._socket.settimeout(0.1)

    def __enter__(self):
        self._reading_thread = threading.Thread(target=print_recv, args=(self._socket, self._event))
        self._reading_thread.start()
        return self._socket

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._event.set()
        # Waiting for thread termination so there is no OSError when closing the socket
        self._reading_thread.join()
        self._socket.close()

Now all what is left to do is to send messages from stdin to the netcat server. Using the above context manager, it should look like the following:

def netcat_session(rhost, rport):
    with NetcatManager(rhost, rport) as netcat_socket:
        # Process stdin and use netcat_socket.send

And that’s it.

Now, on the topic of processing stdin, be aware that Ctrl+C (which is translated to KeyboardInterrupt) does not mean EOF: Ctrl+D does. So catching the KeyboardInterrupt is meant to recover from an unusual termination of the program; it may or may not be what you want.

Putting everything together, we can come to:

import sys
import socket
import threading

class NetcatManager(object):
    def __init__(self, rhost, rport, timeout=0.1):
        self._event = threading.Event()
        self._socket = socket.create_connection((rhost, rport))
        self._socket.settimeout(timeout)

    def __enter__(self):
        self._reading_thread = threading.Thread(target=print_recv, args=(self._socket, self._event))
        self._reading_thread.start()
        return self._socket

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._event.set()
        # Waiting for thread termination so there is no OSError when closing the socket
        self._reading_thread.join()
        self._socket.close()

def print_recv(sock, event):
    while not event.is_set():
        try:
            msg = sock.recv(4096)
        except socket.timeout:
            pass
        else:
            if not msg:
                break
            sys.stdout.write(msg)
            sys.stdout.flush()

def netcat_session(rhost, rport, input_file=sys.stdin):
    with NetcatManager(rhost, rport) as netcat_socket:
        # We do not iterate (for line in input_file) because stdin does not behave well in Python 2
        while True:
            line = input_file.readline()
            if not line:
                # EOF reached
                break
            netcat_socket.sendall(line)
    # Leave with the screen in a clean state
    print

Note the use of default values. You can now provide any file-like object as the third parameter of netcat_session and it will send instructions from there (so you can save a test session in a file and replay it over and over again using with open('the_file.txt') as f: netcat_session('localhost', 5555, f)).


Print output one word per line - K&R Exercise 1-12

include <stdio.h>

You're missing a # there, copy/paste issue?

main()

That's been out of style for a very long time, and is in fact no longer valid according the standard (from C99 and on). Always specify the return type (for main and all other functions).

int main()

int c;

c = 0;

Don't keep uninitialized variables around for any length of time if you can avoid it. A bit trivial here, but nonetheless prefer:

int c = 0;

In this specific case, as Jonathan Leffler pointed out, you're unconditionally initializing c in the very next line, so the initialization is not necessary.

(Starting with C99, you can declare variables as you need them. You don't have to stack them all at the top. So as far as possible, only declare variables at the point where they are needed and initialize them at the same time.)

if (c == ' ')
 putchar('\n');
else
  putchar(c);

Your indentation's out of whack here, the first putchar should be indented one with one more space.

As for "bugs", your program won't print what is usually expected if, summarizing points made in Stat1c_V01D's answer and comments by Jonathan:

The input contains empty lines. You'll output empty lines too. They should be omitted.
The input contains whitespace other than plain spaces and newlines (e.g tabs or form feeds). Your code will not split those out. Look at isspace.
The input contains consecutive whitespace characters. Your program will output consecutive new lines between words.
The output doesn't end with a \n. Your program won't output one either which is "bad form". On a Unix terminal, you'll end up with no newline between the last word output and the new prompt.

That's why extra bookkeeping is needed in the solutions you find for this exercise.


Deserialize JSON Strings Directly into Models?

TheJSON schema and data class attributes are unlikely to change. Consider implementing the class to encapsulate the JSON hash, adapting it to the ruby idioms and whatever other custom operations you've added. This should greatly decrease the cost and complexity of deserialization.