Well, you're off to a good start, I think. Only one major thing comes to mind, when I read your code.

Tuples

Instead of operating on seqs or similar, use a tuple. The size of a tuple is fixed and known at compile time. In this game, you know you'll always consider three cards at a time, so it fits the bill. This will also help simplify your allEqual and allDifferent functions. The isSet function still works, as the parameter l is now a tuple instead of a seq.

let allEqual (c1, c2, c3) = c1 = c2 && c2 = c3
let allDifferent (c1, c2, c3) = c1 <> c2 && c2 <> c3 && c1 <> c3

This affects the shape of your compare function as well. The line

let colorSet = cardList |> List.map (fun c -> c.Color  ) |> isSet

now becomes like

let colorSet = isSet (card1.Color, card2.Color, card3.Color)

and similar for shapeSet, patternSet and numsSet. Now the cardList variable may be removed, and the compare function is short and to the point.

Abstracting the isSet function

Suppose you think the way the colorSet, shapeSet, etc. variables are defined looks to clunky. You could abstract away the commonalities, by defining a function for getting the Color property and so on. These could then be supplied as arguments to the isSet, allEqual and allDifferent functions . Like this:

let color c = c.Color
// ...
let allEqual feature (c1, c2, c3) = feature(c1) = feature(c2) && feature(c2) = feature(c3)
// ...
let cards = (card1, card2, card3)
let colorSet = isSet color cards
// ...

I've only shown a couple of the required functions above, but I hope you get the point. In a small example like this, this might be overkill, but had you had many more features, I would probably go that way.

Discriminated unions

One last point is, that it would be obvious to use discriminated unions instead of string and int. I.e. you could define types for each feature, and use them in the Card definition

type Color = Green | Blue | Red
type Number = One | Two | Three
// ...
type Card = { Color: Color; Number: Number; ... }

This will help readability of your code. Furthermore, if this should interact with the outside would, where input comes in the shape of strings, it pushes parsing and validation to the boundary layer.


1. Review

There are a couple of print statements that seem to be left over from a debugging session. If you want to trace the execution of a Python program, you can do so without editing the code, by using the Python debugger. This would avoid the risk of forgetting to remove your debugging code.
There is no need for the special case:

if len(s) <= 1: return 0

since these cases are handled correctly by the rest of the code.
There is also no need for the special case:

if s[i-1] == "(":

since if you look at the two branches you'll see that they do the same thing.
The algorithm is slightly tricky so I would like to have a comment explaining the values that we are going to put in the array longest:

# longest[i] will be length of longest valid substring ending at i.

The expression i - longest[i-1] - 1 appears in several places so would benefit from being stored in a variable:

# Index where matching ( would have to be, if it exists.
j = i - longest[i-1] - 1

The test i-longest[i-1]-2 >= 0 becomes j-1 >= 0 and this can be simplified to j > 0 to avoid the subtraction, and then just to j since you have already tested j >= 0.
We can avoid testing j at all by noting that if it is 0 then j-1 is -1 and longest[-1] is still a valid lookup, getting the last entry of the array longest, which is 0 as required.
The line:

if longest[i] > max_len: max_len = longest[i]

can be simplified using the built-in max:

max_len = max(max_len, longest[i])

Instead of maintaining a running maximum, just run max once at the end:

return max(longest, default=0)

This requires Python 3.4 or later, for the default argument. On earlier versions of Python you'd have to write something like:

return max(longest) if longest else 0

2. Revised code

# longest[i] will be length of longest valid substring ending at i.
longest = [0] * len(s)
for i in range(1, len(s)):
    if s[i] == ')':
        # Index where matching ( would have to be, if it exists.
        j = i - longest[i-1] - 1
        if j >= 0 and s[j] == '(':
            longest[i] = 1 + i - j + longest[j-1]
return max(longest, default=0)


For hash brute-forcing, the short answer is "don't do it in Python". You'll get massive performance gains in switching to C or C++.

Since this is for learning purposes, reviewing your Python:

For legibility, add a newline between your imports and your code.
Consider putting your global-scope code into a main() function plus subdividing some of the code into other functions.
Does your code actually run? You have a loop on ready, but you don't modify its value, so I think it's going to hang there. I suspect that you've broken your loop's indentation, and that some statements below belong in the loop.
Instead of setting ready to later break out of the loop, you can simply break. You can get rid of your else/continue.


Given a string, print another one without a given char

Passing strings and buffers in C is a pain.  For this problem, it would be idiomatic to write a function that accepts an in-out parameter — basically a mutable string.  It works well in this case because you know that the result will never be longer than the original string.

char *deleteChars(char *s, char c) {
    char *out = s;
    for (char *in = s; *in; in++) {
        if (*in != c) {
            *out++ = *in;
        }
    }
    *out = '\0';
    return s;
}

If the caller wants to obtain the result as a separate string, then let the caller duplicate the string before calling deleteChars().


MIPS assembly program to read integer byte by byte

Firstly, you're missing some closing quotes on the data declarations at the top of the file. And you should specify that you make use of MARS specific calls.

However, when you read an integer using the "read integer" call, you read an 8-bit integer, that is, ranging from 0 to 255.

In your program you attempt to print four bytes out of this single byte, and therefore your program will print out garbage to the console.

You should simply remove the code that prints B2, B3 and B4.


Data transformation using Lodash in a more readable way

Take advantage of lodash's _() wrapper function, which wraps a value, and allows chaining of methods.

function grouper(screenshotsArray){
  return _.reduce(screenshotsArray, function(templateDevicesName, screenshot) {
    return templateDevicesName + ' + ' + screenshot.device;
  }, '');
}

var transformedData = _(templates).map('screenshots').groupBy(grouper).value();


def brace_check(string):

string is the name of a python module, it might be best to avoid it

    # Imports
    import re

imports should be done at the module level not inside a function

    # Configuration
    charset = dict(opening='{[(<',\
        closing='}])>',\
        string = ['"', "'"],\
        single=['#', '//'],\
        multi=[['/*', '*/'], '"""', ['<!--', '-->']])

Constant values should be at the module level not inside the function

    found = []# found objects

found isn't used until way later. Declare it way later.

    notr = []# busy locations

notr and its comment don't suggest anything the same.

    temp = {}# temporary holding for opening braces
    end = {}# temporary holding for closing braces

All variables are temporary. Don't give names or comments that tell me such obvious things

    # Find all ocurrances and its position
    newline = [m.start() for m in re.finditer('\n', string)] # every newline

    for mn in charset['multi']:# find every multiline comment
        if type(mn) == type(str()):# if there only is one element
            op = [m.start() for m in re.finditer(re.escape(mn), string)]
            cl = op[1::2]
            op = op[0::2]
            mn = (mn, mn)

        else:
            op = [m.start() for m in re.finditer(re.escape(mn[0]), string)]
            cl = [m.start() for m in re.finditer(re.escape(mn[1]), string)]

These short cryptic variables name are asking for confusion.

        for i in xrange(len(op)):# find and close every comment
            om = op[i]

Use the enumerate function. It lets you use a foreach loop and get the indexes at the same time
                try:
                    cm = next(v for v in cl if v > om) + len(mn[1])

add a line like: start_comment, end_comment = mn, that way you can avoid the indexes are your code will be clearer.

                if mn[0][0] in charset['opening'] and\
                        mn[1][-1] in charset['closing']:
                    for i in xrange(om + 1, cm - 1):
                        if i not in notr:
                            notr.append(i)

Rather the constantly checking whether a value is in notr, use a set. Then the last three lines can simply be notr.add( xrange(om + 1, cm - 1) )

                else:
                    for i in xrange(om, cm):
                        if i not in notr:
                            notr.append(i)

Did we really need that special case?

            except:

Don't catch all exceptions, you'll hide bugs that way. Instead, catch only the specific type of exception you are interested in. Also, you want as little code in the try block as possible to avoid catching other stray exceptions

                for i in xrange(om, len(string)):
                    if i not in notr:
                        notr.append(i)

You at least need a comment explaining why this make sense.

        del op, cl

Don't del variables, its rarely useful.

    for sn in charset['single']:
        rep = [m.start() for m in re.finditer(re.escape(sn), string)]
        for s in rep:
            try:
                new = next(v for v in newline if v > s)
            except:
                new = len(string)
                newline.append(len(string))

Why not use the string search functions rather then having built a newline list? Also, if you need to treat the end of input as a newline, put that in when you create the list not in an exception handler.

            if not s in notr:
                for i in xrange(s, new):
                    if i not in notr:
                        notr.append(i)
                newline.remove(new)
        del rep

    for sn in charset['string']:
        rep = [m.start() for m in re.finditer(re.escape(sn), string)]
        last = False
        for i in xrange(len(rep)):
            if not last:
                s = rep[i]
                if s not in notr:
                    try:
                        new = next(v for v in newline if v > s)
                    except:
                        new = len(string)
                        newline.append(len(string))

If code repeats, you need a function.

                    try:
                        n = next(v for v in rep if v > s)
                    except:
                        n = new + 1
                    if n < new:
                        last = True
                        for i in xrange(s, n + 1):
                            if i not in notr:
                                notr.append(i)
                    else:
                        for i in xrange(s, new):
                            if i not in notr:
                                notr.append(i)
                        newline.remove(new)
            else:
                last = False
        del rep

    for cn in charset['closing']:
        on = charset['opening'][charset['closing'].find(cn)]
        end[on] = [m.start() for m in re.finditer(re.escape(cn), string)\
            if m.start() not in notr]

Given the cn is a single character, use of a regular expression to find it is overkill.

    for on in charset['opening']:
        op = [m.start() for m in re.finditer(re.escape(on), string)\
            if m.start() not in notr]
        for i in xrange(len(op)):
            temp[op[i]] = on

    for k in sorted(temp.keys(), reverse=True):
        try:
            c = next(v for v in end[temp[k]] if v > k and v not in notr)
            end[temp[k]].remove(c)
            for i in xrange(k, c + 1):
                if i not in notr:
                        notr.append(i)
        except:
            c = False
        found.append((k, c))

It seems to me that using a stack would be simpler then what you are doing here.

    for v in end.values():
        for c in v:
            found.append((c, False))

No explanation is given for what you are putting inside found. I have no idea what the return value means.
        return found

General thoughts:

The code is complicated, it really should be split up into a lot of functions.

Rather then all that code matching different types of comments and strings, have a set of ignore regexes. The regex should match an entire comment or string which can then be removed.

Your code builds lists of everything which would only serve to complicate what is going on. Lists can be great, but they aren't the solution to every problem.

My rewrite of your code: (I didn't start with your code, but it should support the same features:)

from nose.tools import assert_equal
import re

class SimpleTokenizer(object):
    """
    The constructor takes a dictionary of keys which should be regular
    expression strings to arbitrary value. The tokenize method will produce
    all the substrings in the text which match the regular expression.
    It will return the value provided in the original dictionary
    to identify which expression was matched
    """
    def __init__(self, data):
        # I need a consistent order from data, so I dump the dictionary
        # into a list
        data = list(data.items())
        self.values = [value for key, value in data]
        # this regular expression matches any key
        self.expression = '|'.join('(%s)' % key for key, value in data)

    def tokenize(self, text):
        for match in re.finditer(self.expression, text):
            # group 0 is the whole string, we subtract one
            # to make up for that
            yield match.start(), self.values[match.lastindex - 1]

CLOSER = 0
OPENER = 1
IGNORE = 2
class Language(object):
    """
    Provides brace checking
    """
    def __init__(self, opening, closing, ignore = ()):
        """
        opening and closing should be sequences of the same size denoting
        the start and end symbols that should matched. Ignore should be a
        sequence of regular expression which should be ignored for the
        purpose of matching such as comments, strings, etc.
        """

        data = {}
        for opener, closer in zip(opening, closing):
            data[re.escape(opener)] = (OPENER, closer)
            data[re.escape(closer)] = (CLOSER, closer)
        for ignore in ignore:
            data[ignore] = (IGNORE, None)
        self._tokenizer = SimpleTokenizer(data)

    def check(self, text):
        """
        Given text produces the location of the various braces
        returns a list of tuple, start, end where a pair of matches
        braces exist. If either brace is missing it will be recorded
        as None.
        """

        braces = []

        waiting = []
        # waiting is a stack holding the braces which have been opened
        # but not yet closed
        for idx, (category, extra) in self._tokenizer.tokenize(text):
            if category == OPENER:
                waiting.append( (extra, len(braces)) )
                # we start with None as the end of a brace, it'll be
                # updated if we find it
                braces.append( (idx, None) )
            elif category == CLOSER:
                # find the last entry that matches
                index = None
                for element, element_index in reversed(waiting):
                    if element == extra:
                        index = element_index
                        break

                if index is None:
                    # no matches found
                    # in that case, record the start as None
                    braces.append( (None, idx) )
                else:
                    # we found the match, replace the existing record
                    # with a new one
                    position, waste = braces[index]
                    braces[index] = (position, idx)
                    # elminate anything we had to ignore
                    del waiting[index:]

        return braces

LANGUAGE_TESTS = [
    ("[()]", [(0, 3), (1, 2)]),
    ("[(a)]", [(0, 4), (1, 3)]),
    ("[(]", [(0, 2), (1, None)]),
    ("[()", [(0, None), (1, 2)]),
    ("[(])", [(0, 2), (1, None), (None,3)]),
    ("])", [(None, 0), (None, 1)]),
    ("(])", [(0, 2), (None, 1)]),
]

def test_basic_language():
    language = Language(
        opening = '[(',
        closing = '])')
    def inner(text, expected):
        result = language.check(text)
        assert_equal(list(result), expected)

    for text, expected in LANGUAGE_TESTS:
        yield inner, text, expected

STRING_LANGUAGE = [
    ('[(")]")]', [(0, 7), (1, 6)])
]
def test_string_language():
    language = Language(
        opening = '[(',
        closing = '])',
        ignore = [r'"[^"]*"']
    )
    def inner(text, expected):
        result = language.check(text)
        assert_equal(list(result), expected)

    for text, expected in STRING_LANGUAGE:
        yield inner, text, expected


PHP Validation with functions and list()

This might not be what you are looking for but I recently wrote this code to validate my forms.

As you might notice I define the data to be validated in the $validate array. Then some loops run through them and show the proper errors. If no errors are found, it sends the form.

With some modifications, you could probably use something similar. Hope it helps.

<?php

    # post data collection
    $name   = "Full name";
    $email  = "a@b.c";
    $age    = "193";
    $x      = "s";
    $y      = "s";

    # select data that needs validation
    $validate   = array(
        'required'      => array($name, $email, $x, $y),
        'validEmail'    => array($email),
        'validNumber'   => array($age),
        'validAlpha'    => array($name)
    );

    # error messages
    $errorsMsgs = array(
        'required'      => 'Please fill out all required fields.',
        'validEmail'    => 'is an invalid email address.',
        'validNumber'   => 'is an invalid number.',
        'validAlpha'    => 'contains invalid characters. This field only accepts letters and spaces.'
    );

    $errorMarkup    = "
We found a few errors :-(

Please fix these errors and try again

";
    $successMarkup  = "
Success!

Your form was sent successfully.
";
    $backMarkup     = "Back to form";

    # begin state
    $valid = true;

    # loop through fields of error types
    foreach ($validate as $type => $fields) {
        # loop through values of fields to be tested
        foreach ($fields as $value) {
            # throw error if value is required and not entered
            if ($type === 'required' && strlen($value) === 0) {
                $errorMarkup .= "
$errorsMsgs[$type]
";
                $valid = false;
                break;
            }
            else if (
                        $type === 'validEmail'  && !filter_var($value, FILTER_VALIDATE_EMAIL) ||
                        $type === 'validNumber' && !preg_match('/^[0-9 ]+$/', $value) ||
                        $type === 'validAlpha'  && !preg_match('/^[a-zA-Z ]+$/', $value)
                    ) {
                if (strlen($value) === 0) {break;} # skip check if value is not entered
                $errorMarkup .= "
\"$value\" $errorsMsgs[$type]
";
                $valid = false;
                continue;
            }
        }
    }

    if ($valid) {
        # email form
        $body = $successMarkup . $backMarkup;
        $title = "Form sent";
    } else {
        $body = $errorMarkup . "
" . $backMarkup;
        $title = "Form errors";
    }

    # write html ouput
    echo "<!DOCTYPE html><title>$title</title>$body";
?>


CROSS JOIN solution for records "missing" from a link table

I am pretty sure that this is the right approach to solve this problem, but depending on the RDBMS, it is not necessary the use of any index to access each row.
Oracle, for instance, will probably operate with Hash Joins in this case, because of the high  cardinality of the query (at the end of this task all rows of this 3 tables must be accessed) and if you have an index on the link table, it will use an Index Fast Full Scan.
I don't know if other RDBMS have the power of Hash Joins operations, which uses more memory instead of IOs.

Another syntax that could be used in this problem is the NOT EXISTS operator. Choose which syntax you think will translate more clearly the meaning of the query. In Oracle it will forces to perform an Hash Join Anti operation in the last table.


If you're after speed, I'd suggest scrapy. I was looking for an excuse to try it out and saw your question. When I ran your code on the first 10 pages of the NA leaderboard, it took a little over 4 seconds. Running the below takes about 0.3 seconds, presumably due to initiating all the HTTP requests in parallel:

test.py:

class LolSpider(scrapy.Spider):
    name = 'lolspider'
    start_urls = ['http://lolprofile.net/leaderboards/na/{}'.format(page) for page in range(10)]

    def parse(self, response):
        for name in response.xpath('//a[re:test(@href, "http://lolprofile.net/summoner/")]//text()').extract():
            yield { 'name': name }

Running:

$ scrapy runspider test.py -o names.json

names.json:

[
{"name": "<first name here>"},
{"name": "<second name here>"},
...
]

To actually provide some code review feedback:

import requests # I prefer this and then requests.get over "from requests import get", since "get" is too common a word
from bs4 import BeautifulSoup
import time # ditto here
import re # and here

print('***PYTHON LEAGUE OF LEGENDS USERNAME SCRAPER***')
print('This script scrapes usernames from lolprofile.net')
region = input('Enter the region for scraping(eune/euw/na/br/tr/kr/jp/lan/las/oce/ru)\n')
num_start = int(input('What page to start on? Min 0\n')) # cast to int once here
num_end = int(input('What page to end on? Min starting page + 1\n')) # ditto

size = 0 # use a simple count rather than a list

# Python style dictates snake case
# get the URL rather than set a global variable
def get_url(page_num, region):
    # use string formatting rather than concatenation
    return 'http://lolprofile.net/leaderboards/{}/{}'.format(region, page_num)

def is_ascii(i):
    return all(ord(c) < 128 for c in i)

start = time.time()

# for loop instead of while avoids the need to increment by hand
for page_num in range(num_start, num_end + 1):
    url = get_url(page_num, region)
    print(size)
    html = requests.get(url).text
    soup = BeautifulSoup(html, "html.parser") # html.parser
    # /.* (slash and then anything) rather than /* (any number of slashes) in the regular expression
    user_names = [a.string for a in soup.findAll(href=re.compile('http://lolprofile.net/summoner/.*'))]
    with open('usernames1.txt', 'a') as file:
        for i in user_names:
            if is_ascii(i) and ' ' not in i: # not in
                file.write('%s\n' % i.lower())
                size += 1

end = time.time()

print('{} usernames scraped in a total of {} seconds.'.format(size, end-start))


Expanding powers of expressions of the form ax+b

You don't need the special case for k == 0. When k == 0, the result of the other expression will be 1 as well.

For this sequence of binomial coefficients you don't need to calculate the full fak expression each time. You can also start with c = a ** i, and then, for each k, multiply by (n - k) / (k + 1) * b / a. That's a bit faster and provides less risk of producing numeric overflows, which would result in slightly incorrect coefficients. The Wikipedia article on binomial coefficients should explain this in more detail.


Here you are creating a node unnecessarily:

   TreeNode* tn = new TreeNode(0);
    tn=root->right;

You could write simpler as:

   TreeNode* tn = root->right;

Because you're not using the original value of tn anyway, you only need it as a work variable for swapping the left and right nodes.

Also, your implementation doesn't use the return value of the recursive invertTree calls. You can use them better and get rid of the conditional statements, making the solution more compact:

TreeNode* invertTree(TreeNode* root) {
    if (root == NULL) {
        return NULL;
    }

    TreeNode* work = root->right;
    root->right = invertTree(root->left);
    root->left = invertTree(work);
    return root;
}

   I think I am invoking undefined behavior when the control hits the leaf nodes.

No, you're not invoking "undefined behavior" when hitting the leaf nodes. Actually I think you meant to say intermediary nodes. At leaf nodes, the function receives a null node and you return null. At intermediary nodes, you allocate an unnecessary node, as explained earlier. The unnecessary allocation doesn't trigger an undefined behavior, but since you never free the allocated memory, this is a memory leak, and indeed a problem if the program was used for a substantial amount of time, accumulating unreleased memory.


Algorithm Improvement - element differences in list

One simple observation is that this problem gets much easier if you sort nums O(n log(n). Then you can use bisect_left which uses binary search to find where an element would go in a sorted list and is O(log(n)) for each element in m. This yields a total time of O((n+m) log(n))

from bisect import bisect_left

def sol_sorted(nums,maxes):
    output = []
    nums.sort()
    for m in maxes:
        ind = bisect_left(nums, m)
        output.append(len(nums) - ind)
    return output


This isn't really F# specific because you could do the same thing in your C# code, but converting each character to a string so you can parse it as an integer seems inefficient to me. I'd be inclined to use Char.GetNumericValue instead.

Also, you could eliminate a step in your method chain by using Seq.sumBy instead of Seq.map + Seq.sum.

I might write your code like this:

open System

let calcCheckDigit rt =
    let s =
        rt
        |> Seq.map (Char.GetNumericValue >> int)
        |> Seq.zip [3;7;1;3;7;1;3;7]
        |> Seq.sumBy (fun (a,b) -> a * b)
        |> float
    (s / 10.0 |> ceil) * 10.0 - s |> int

In my opinion, separating out the "convert a character to an integer" from the multiplication makes it easier to read. I'm using the function-composition operator to join together the Char.GetNumericValue and int functions in sequence, and then passing the resulting combined function into Seq.map.

On the last line, it's a little ambiguous just what value is being passed into ceil. It would be easy for someone unfamiliar with the code to assume that the result of the entire expression (s / 10.0) * 10.0 - s is being passed to ceil. I would be inclined to write that as I did above (obviously) but if you don't like that use of the pipe operator then I think this would also be a little more clear: int ((ceil (s / 10.0)) * 10.0 - s). Personally I'm not a fan of lots of nested parens, but to each their own.

(Before I edited this post, I mistakenly assumed exactly what I just mentioned, and so I wrote (s / 10.0) * 10.0 - s |> ceil |> int. Then I realized it wouldn't produce the same output as the C# version.)


In VB2010 the instr out performed indexof

    Dim ipsum As String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

    Dim tries As Integer = 100000
    Dim stpw As New Stopwatch
    Dim iof As Integer
    Dim f As String = "sint"

    stpw.Reset()
    stpw.Start()

    For x As Integer = 1 To tries
        iof = ipsum.IndexOf(f)
    Next
    stpw.Stop()
    Label1.Text = stpw.ElapsedMilliseconds.ToString("n2")

    stpw.Reset()
    stpw.Start()

    For x As Integer = 1 To tries
        iof = InStr(ipsum, f)
    Next
    stpw.Stop()
    Label2.Text = stpw.ElapsedMilliseconds.ToString("n2")


Encryption via multiplication of hex-converted, multiplied ASCII values

I don't do security.
The information is provided as if this were not a security problem.

First things first. Python's random number generation is pseudo-random.
The source code is really small, and consisted of iirc 4 %.

If we look at the docs for what this may mean on your security.

  Warning: The pseudo-random generators of this module should not be used for security purposes.
  Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.

That instantly destroys all the security of this security program.

Style

PEP8

There should be two blank lines either side of top level functions or classes.
You need white space after commas. [1, 2].
random_key = [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]
You should have one space either side of operators. 2 * 2.
The exception to this is so show precedence. 2*2 + 2.
'\n'*3

General style

You should use better variable names. x is not descriptive. lst and lst2 don't 'say' what they do.

When using range 0 is the default value for start. range(0, len(password)-1) == range(len(password)-1).

You should not have all your code in the top level of the program. As a minimum you should wrap it in a if __name__=='__main__':. And then you should have it so that it calls main().

Code

There are two features of the language that you should really like.

1. List comprehensions.

lst = []
for i in range(0, len(password)-1):
    lst.append(ord(password[i]))

Using a list comprehension, you can simplify this.

lst = [
    ord(password[i])
    for i in range(len(password)-1):
]

You can then just slice the string.

lst = [ord(char) for char in password[:-1]]

2. str.join:

result = []
for e in lst:
    result.append(e)
    result.append('|')
result.pop()

This can simply be reduced to

result = '|'.join(str(char) for char in lst)

Conclusion

If we simplify everything, and remove the prints, we get the following:

def get_hexes():
    return [hex(random.randint(1000,2000)) for _ in range(4)]

password = getpass.getpass('Please input a password.\n')
key = input('Please pick a list number. Write it down!!')
x = random.randint(1,1000)

lst = get_hexes() + [hex(ord(char) * x) for char in password[:-1]] + get_hexes()
lst[key] = hex(x)
result = '|'.join(str(char) for char in lst)

path = '/home/vhx/Documents/code/tkinter/encryption/password.txt'
with open(file, 'w') as target:
    target.truncate()
    target.write(result)

From this, we can tell easily, that it's not that secure.
You know that the | and the first and last 4 sections are just red herrings.
This is as they are always just there and we can ignore them.
And there is a lot more noise than needed, 0x.

And, the password will always have a character missing, and can have another missing.

I think the best example of a good password and list number is aa and 5. This is as then my password will be any two letters. All I need to remember is 5.

Also, you can tell when the key is in the first or last 4 sections, this is as the minimum for them are 1000, where the maximum for the key is 1000.

If you want better feedback on your algorithm, go to the cryptography site.


Thanks for submitting your code for review — it shows that you care about code quality and you're willing to improve and learn.
Note that OOP stands for object-oriented programming and does not have a plural form ;-)

Alexandre has given you some good advice and one possible implementation. I'd like to critique your code a bit more thoroughly and offer another, more lightweight possibility.

Criticism

Concept

An important idea in software development is that code should be reusable. Your code seems like a specific application of a general idea that applies not only to throwing the dice but just as well to tossing a coin or drawing a card (and gathering statistics).

So you should consider designing your code in a way that allows it to work for all these (and other) scenarios. That is to say, the number of elements in the input sequence (currently 6) and the element names themselves (currently {1,2,3,4,5,6}) should be configurable by the caller of the code.

Separation of concerns

I'll keep this part short since Alexandre has already elaborated on it. Just remember a few key points:

Never put any user interface related code into your core business logic (RandomDice class)
If you mix up these concerns, you'll find it hard to reuse your code for applications based on other UI frameworks than the Console (for instance, Swing, SWT or AWT or Servlets).
Instead of outputting data, use return values
Just replace occurrences of System.out.println with an appropriate return value (e.g. String)
Choose one responsibility per object and refactor others into new objects
The class that calculates the statistics should not be in charge of formatting the output —  you need to introduce a new Collaborator (an object that encapsulates that responsibility)

Comments

Use them sparingly or they will cause clutter and be ignored
Check your spelling and grammar

amount of times should be number of times
stimulating should be simulating

Format them properly
For summaries above class and method definitions (don't put them between package and import but directly above the relevant code!) always use the same (Javadoc) syntax:

/**
 * This program will help you to imitate the randomness of a dice roll,
 * and to represent the frequency of each face appearing in a tabular form.
 */

Choose better names to avoid writing a comment

Naming

Be expressive and avoid junk names such as arg0 or arg1
Instead of the following obsolete comment:

// / the method below takes an argument arg0 which indicates the amount of
// times the dice has to be rolled.
public void roll(int arg0) {
    diceRoll = arg0;

Why not get rid of the field diceRoll and write

public void roll(int numberOfTimes) {

Avoid stating the obvious (that applies to comments, too!)
Dice can reasonably be assumed to be random, so RandomDice is unnecessary
MainClass also states the obvious, just use Main
Follow conventions (methods and variables are camelCase, classes are PascalCase)

Also

Always specify access modifiers
Use the most restrictive access modifier possible (in your code, rand was accessible from other classes!):
Don't declare your arrays C-Style (keep the data type before the variable instead)

int ObservationArray[] = { 0, 0, 0, 0, 0, 0 }; // don't do this
int[] ObservationArray = { 0, 0, 0, 0, 0, 0 }; // this form is clearer

Alternative implementation

By refactoring step-for-step and slowly introducing changes, I arrived at the implementation shown below that aims to illustrate the points made in this answer. RandomDice was renamed to DistributionCalculator and is now generic (it can work with any type of elements, as illustrated in the Usage section). It accepts an Array of elements in the static convenience method with. After initialization, the frequencies can be calculated by calling calculateDistribution.

That method returns a Distribution<K,V> which is the class that encapsulates the string formatting (I went ahead and made the output a bit more pretty).

The naming could probably be more accurate from a mathematical perspective — go ahead and rename things if you feel that these terms aren't quite correct (probably UniformDistributionCalculator or something would have been more exact).

The frequencies are now stored as longs to allow for bigger calculations, though that can be changed easily if you don't agree with the decision.

If something requires further explanation, go ahead and ask in the comments.

Usage

public class Main {
    private static final Scanner scan = new Scanner(System.in);
    private static long iterations;

    public static void main(String args[]) {
        System.out.print("Please enter the number of times you want to iterate: ");
        iterations = scan.nextLong();
        test(DistributionCalculator.with(1, 2, 3, 4, 5, 6));
        test(DistributionCalculator.with("hearts", "spades", "clubs", "diamonds"));
        test(DistributionCalculator.with(true, false, null));
    }

    private static <T> void test(DistributionCalculator<T> calculator) {
        System.out.println(calculator.calculateDistribution(iterations));
    }
}

Output

 Please enter the number of times you want to iterate:  200000

 element             frequency
 1                   33129
 2                   33156
 3                   33539
 4                   33469
 5                   33346
 6                   33361

 element             frequency
 hearts              50100
 diamonds            49857
 spades              49752
 clubs               50291

 element             frequency
 null                66560
 false               66726
 true                66714

Calculation of frequencies

public class DistributionCalculator<T> {

    private static final Random random = new Random();
    private final Map<T, Long> map = new HashMap<T, Long>();
    private final T[] keys;

    public static <T> DistributionCalculator<T> with(T... elements) {
        return new DistributionCalculator<T>(elements);
    }

    private DistributionCalculator(T... elements) {
        keys = elements;
        for (T key : keys) {
            map.put(key, Long.valueOf(0));
        }
    }

    public Distribution<T, Long> calculateDistribution(long numberOfIterations) {
        for (long i = 0; i < numberOfIterations; i++) {
            T key = keys[random.nextInt(keys.length)];
            map.put(key, map.get(key) + 1);
        }
        return new Distribution<T, Long>(map);
    }
}

Result formatting

public class Distribution<K, V> {
    private final Map<K, V> map;
    private final String table;

    public Distribution(Map<K, V> distribution) {
        map = distribution;
        table = generateTable();
    }

    public Map<K, V> asMap() {
        return map;
    }

    @Override
    public String toString() {
        return table;
    }

    private String generateTable() {
        final String line = "%n%-20s%s";
        String result = String.format(line, "element", "frequency");
        for (K key : map.keySet()) {
            // it would be better to use a StringBuilder if you have a lot of keys
            result += String.format(line, key, map.get(key));
        }
        return result;
    }
}


Notes about your code

You can also simplify the way you look for the links to follow:

for link in soup.select("a[href]"):
    downloadImages(link["href"], level - 1)

Here, we are enforcing the a elements to have href values, not checking for elements to be found (since the loop body would just not be executed in this case).
As far as managing the urls you've already visited:

don't use globals
use a set instead of a list for faster lookups

It's also a good practice to always specify the parser BeautifulSoup uses under-the-hood:

soup = BeautifulSoup(urlContent, "lxml")
# or soup = BeautifulSoup(urlContent, "html.parser")
# or soup = BeautifulSoup(urlContent, "html5lib")

follow PEP8 recommendations - specifically, naming is agreed to be in lower_case_with_underscores format, not camelCase
no need to join the urlContent - simply pass urlContent to BeautifulSoup

Alternative solution

I would implement it this way:

try:
    from urlparse import urljoin
except ImportError:
    from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup

class Scraper:
    def __init__(self):
        self.visited = set()
        self.session = requests.Session()
        self.session.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36"}

        requests.packages.urllib3.disable_warnings()  # turn off SSL warnings

    def visit_url(self, url, level):
        print(url)
        if url in self.visited:
            return

        self.visited.add(url)

        content = self.session.get(url, verify=False).content
        soup = BeautifulSoup(content, "lxml")

        for img in soup.select("img[src]"):
            image_url = img["src"]
            if not image_url.startswith(("data:image", "javascript")):
                self.download_image(urljoin(url, image_url))

        if level > 0:
            for link in soup.select("a[href]"):
                self.visit_url(urljoin(url, link["href"]), level - 1)

    def download_image(self, image_url):
        local_filename = image_url.split('/')[-1].split("?")[0]

        r = self.session.get(image_url, stream=True, verify=False)
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                f.write(chunk)

if __name__ == '__main__':
    scraper = Scraper()
    scraper.visit_url('http://www.yahoo.com', 1)

Aside from things mentioned above, here are some other applied changes:

using requests third-party library with a shared session
Python 2 and 3 compatible
using class for sharing "session" and a set of visited urls
separate methods to visit urls and download images
if __name__ == "__main__": is used to avoid the code being executed on import
changed the way image filename is determined (probably still not the best way)
handling relative urls as well as absolute


First off:

  The only response i can get from the SOAP client except from data in case of success is exceptions.

Of course, if your call wasn't successful, there's something wrong, and an exception should be thrown. If you query for an ID that doesn't exist, don't catch the exception. That means the user has provided your client with invalid data, and its that user who must deal with the problem. Not You.
An API doesn't really deal with that many exceptions. In fact, I'm one of those people who think that a well written, bug free API-wrapper doesn't need exception handling. If the wrapper/client's code is properly put together, exceptions are the result of either bad usage or exceptions being returned by the webservice. Both types of errors should be dealt with by the user.

If you don't want to pass the client to all those classes, the answer is simple: inheritance:

class BaseClient
{
    protected $client = null;//declare your properties!!!
    protected $config = null;
    //use type hints, default = null means you don't HAVE to pass the argument
    public function __construct(\SoapClient $client = null)
    {
        $this->client = $client;
    }
    //lazy-loading getter
    protected function getClient()
    {
        if ($this->client === null)
        {//set client only when it's required
            $this->setClient(
                new \SoapClient($this->config['wsdl'], $config['options']
            );
        }
        return $this->client;
    }
    //public to allow injection
    protected function setClient(\SoapClient $client)
    {
        $this->client = $client;
        return $this;//makes your api chainable
    }
}

Then define all the classes you'll actually be using along these lines:

class DebptorClient extends BaseClient
{
    protected $config = array(//optional
        'wsdl' => 'the specific wsdl',
        'options'=> array()//defaults
    );

    public function get($param, $value)
    {
        $client = $this->getClient();//loads if not yet loaded
        return $client->Debtor_GetData(
            array(
                'entityHandle' => $this->getHandle($param, $value)
            )
        )->Debtor_GetDataResult;
    }
}

And so on.

Now, some actual code-review:

Declare your properties

From the wrapper tag wiki:

  A wrapper is an OOP technique where an object encapsulates (wraps) another object, hiding/protecting the object and controlling all access to it.

By not declaring $this->client, client is effectively added later on in your objects life, which means property lookups will be slower, but more importantly: $this->client will be a public property. If $this->client is public, then you don't have a wrapper because:

  A wrapper [...] encapsulates another object, hiding/protecting the object and controlling all access to it.

Thus, $this->client has to be protected or private.
Next.

Seeing this code worries me:

public function getHandle($param, $value)
{
    switch ($param) {
        case 'number':
            return $this->client->Debtor_FindByNumber(array('number' => $value))->Debtor_FindByNumberResult;
            break;//unreachable statement, btw
        case 'email':
            return $this->client->Debtor_FindByEmail(array('number' => $value))->Debtor_FindByEmailResult;
}

You're expecting the people who are to use your api to know that $param and $value are expected to be. $param has only 2 valid options: number or email. anything else is invalid, yet at no point to you bother to validate the data you're being passed.
When developing an API wrapper, it's not a bad idea to create Argument models:

namespace Soap\Data;
class Argument
{
    private $type = null;
    private $value = null;
    public function __construct($type, $value)
    {
        $setter = 'set'.ucfirst(trim($type));//email becomes setEmail
        if (!method_exists($setter, $this))
        {
            throw new \InvalidArgumentException($type.' is not a valid type for '.__CLASS__);
        }
        $this->{$setter}($value);
    }
    public function setEmail($email)
    {
        if (!filter_var($email, \FILTER_VALIDATE_EMAIL))
        {
            throw new \InvalidArgumentException($email.' is not a valid email address');
        }
        $this->value = $email;
        return $this;
    }
}

This allows you to define methods like this:

public function getByType(Argument $value)

and the Argument class ensures that the data you'll receive is validated properly.

Now, error handling.
That very much depends on how you see your code being used. Is it supposed to be a sort of "module" to be included into various projects, in which case, I'd just throw my exceptions out for the caller to deal with them. Code that is used as a dependency shouldn't have to anticipate all sorts of errors that might occur, that's the users job.

If you want this code to work sort of in the background, You could write your own exceptions (extending from either the base Exception class, or SoapFault) if you wanted to.
You could then register your own exception/error handler and unset/restore the old at lib, and quietly log the exceptions. The user, who will then be left clueless as to what actually went wrong will hate you for this. Having to check the logs constantly is a pain when developing, so add some manual overrides, too

class BaseClient
{
    protected static $exceptions = false;
    public function __construct()
    {
        if (static::$exceptions === false)
        {//static to avoid setting handler more than once
            static::$exceptions = true;
            set_exception_handler(array($this, 'exceptionHandler'));
    }
    public function exceptionHandler(\Exception $e)
    {
        //handle
    }
    public function freeExceptions()
    {
        if (static::$exceptions)
        {
            restore_exception_handler();
            static::$exceptions = false;
        }
    }
    public function __destruct()
    {
        $this->freeExceptions();
    }
}

That's one way of going about your business. Generally, though, I use the occasional try-catch block, if I've created a method that strings together a series of Soap calls, for example, but most of the time I consider Exceptions best handled by the code that invoked the method where the exception is thrown, not by the code that throws the exception.


Convert *.VCF contact file for cellphone import

Your function generate_vcard_contact_string obviously belongs to the Contact class. It even takes a Contact instance as the first argument.

I would actually elevate this to be the magic __str__ method, which is for example called when you do print(contact):

class Contact(object):
    """
    Contains the contact information,
    including a list of phone numbers.

    Arguments:
        object {[type]} -- [description]
    """

    def __init__(self):
        self.FirstName = ""
        self.LastName = ""
        self.Phonenumbers = []

    def __str__(self):
        """
        Generates the vCard string for this contact.
        Will generate a separate vCard for each phone number of the contact.

        Returns:
            string -- the generated vCard string
        """

        base = "\n".join(["BEGIN:VCARD",
                          f"N:{self.LastName};{self.FirstName}",
                          "TEL:{}",
                          "END:VCARD"])

        return "".join(base.format(number) for number in self.Phonenumbers)

You should also place your calling code under a if __name__ == "__main__": guard to allow importing from other scripts without executing the code. It is also complex enough to be encapsulated in its own function, IMO:

def parse_contacts(file_name):
    with open(file_name) as f:
        contact = None
        for line in f:
            # Some lines are build like "item1.TEL;...",
            # remove "item1.", "item2.", to ease parsing
            if line.startswith("item"):
                line = line[line.index(".")+1:]

            if "BEGIN:VCARD" in line:
                # Marks the start of a vCard,
                # create a blank contact to work with
                contact = Contact()

            elif line.startswith("N:"):
                # Line contains a name in the format N:LastName;FirstName;...;...;
                # Only LastName and FirstName will be used
                chunks = line[2:].split(';')
                contact.LastName = chunks[0].strip()
                contact.FirstName = chunks[1].strip()

            elif line.startswith("TEL:"):
                # Line contains a phone number
                # phone number type may be specified by "TYPE=...",
                # currently, TYPE will ne omitted
                # One contact may contain multiple phone numbers.
                number = extract_number(line)
                contact.Phonenumbers.append(number)

            elif "END:VCARD" in line:
                # Marks the end of a vCard,
                yield contact

def main():
    for contact in parse_contacts('contacts.vcf'):
        print(contact)

if __name__ == "__main__":
    main()

Your extract_number function can also be simplified using a single regex:

def extract_number(line):
    """
    Extracts the phone number from a vCard-file line,
    by removing everything but numbers and '+'

    Arguments:
        line {string} -- the line to extract the phone number from

    Returns:
        string -- the phone number
    """
    return re.match(r'TEL:(\+?\d*)', line).groups()[0]


Alternative class to imitate AsyncTask class (deprecated) with Thread and Handler classes

public void execute()
    {
        this.localHandler = new Handler();
        this.onPreExecute(); //onPreExecute Method

        this.localThread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                BackgroundTask.this.doInBackground(); //doInBackground Method
                BackgroundTask.this.localHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        BackgroundTask.this.onPostExecute(); //onPostExecute Method
                    }
                });
            }
        });
        this.localThread.start();
    }

This part would be much easier to read using method references:
public void execute()
{
    localHandler = new Handler();
    onPreExecute();

    localThread = new Thread(this::backgroundExecutor)
    localThread.start();
}

protected void backgroundExecutor() {
    doInBackground();

    localHandler.post(this::onPostExecute)
}

        this.localHandler = new Handler();
        this.onPreExecute(); //onPreExecute Method

One should only use this if it is necessary to differentiate between a local and a member variable. And that should only be necessary in setters and the constructor. You can remove this and remove a lot of noise with it.

        this.localHandler = new Handler();
        this.onPreExecute(); //onPreExecute Method

Comment on why you're doing something, not what you're doing. This comment tells me nothing the code on the left doesn't tell me.

        if(this.localThread.isAlive())
            this.localThread.interrupt();

One should only use curly-braces to make the scopes easily visible and minimize possible scope errors.

Your code has a few problems when it comes to threading. Invoking execute multiple times will reset the local state and will yield inconsistent and potentially unknown results, as localHandler and localThread are getting overwritten with every call (imagine execute being called from multiple threads). That will also impact cancel, as it will only be called on the last run thread. Additionally, calling interrupt might or might not actually end the thread. There is no failsafe way to end a thread except killing the JVM.
Your implementation has similar issues, as it shares state using class members, which means that multiple invocations will lead to lost state and possible confusions (three invocations, the last two fail, but the first one is the last to finish).
What you're trying to do is not easy. I'd recommend looking at the implementation of the AsyncHandler class and getting ideas what they were doing. Depending in your use-case, for example if you have a lot of background actions, you might want instead to utilize a thread-pool, to minimize constantly spinning up threads.


Eliminate code duplication by using function parameters (numbers in function name is usually a bad smell )
Separate calculating/processing data and DOM manipulations

My suggested solution:

function calcTip(bill, percent) {
    return bill * percent / 100;
}

function getMessage(tip, percent) {
    return 'A ' + percent + ' percent tip would equal $' + tip;
}

function updateFunc(billInput, tipSuggestion) {
    // Here I use closure to save billInput and tipSuggestion
    return function(percent) {
        var bill = parseFloat(billInput.value) || 0;
        tipSuggestion.innerHTML = getMessage(calcTip(bill, percent), percent);
    }
}

var tenPerBtn = document.querySelector('.tenPercent');
var fifteenPerBtn = document.querySelector('.fifteenPercent');
var twentyPerBtn = document.querySelector('.twentyPercent');
var customPerBtn = document.querySelector('.customTipBtn');
var bill = document.getElementById('billInput');
var tipSuggestion = document.getElementById('tipAmount');

var update = updateFunc(bill, tipSuggestion);

tenPerBtn.addEventListener('click', function() { update(10); });
fifteenPerBtn.addEventListener('click', function() { update(15); });
twentyPerBtn.addEventListener('click', function() { update(20); });
customPerBtn.addEventListener('click', function() { update(document.querySelector('#customTip').value); });


Regex to parse horizontal rules in Markdown

Congratulations, what you have here is a case of really really bad backtracking.  Remember the StackOverflow outage in July 2016? Because it's explained quite nicely there.

regex101 is so kind as to tell us in the debugger view how many steps the regex takes until it matches. In case you were wondering, it's 111,803

We can drastically reduce the number of steps by removing alternative paths from the matcher graph . This can be done by eliminating optionals, dropping non-greedy quantification and some other hacks. In this case we can use a simple trick that's related to the fact that we should only allow a single space in between the asterisks,dashes and underscores:

/^( ?[-_*]){3,} ?[\t]*$/

Already cuts down the recognition of the pattern mismatch in your example to a measly 272 steps.  Do note that I took the liberty of replacing your ORing capture group with a significantly "easier" character class. The functionality is basically equivalent, if we ignore the fact that the capture group you use results in mismatching and additional steps.
This change makes it easier for the regex-engine to determine a match.

The only significant difference between your pattern and mine is that mine doesn't recognize the "non-standard" (as far as that's defined in markdown):

-  -  -
- - - // as opposed to this with only one space between dashes

well and the fact that it doesn't exhibit catastrophic backtracking :) check it out on regex101


I've solved that problem in java and c++ (2nd and 3th places in best solutions category :) so I can compare the local and the remote execution time in order to see - how much faster should be your solution in order to pass.

So, the local execution time of my java solution is 78 ms for the such testcase (10 pairs x 2000 chars), the robot's time is 500 ms, so my PC is ~6.5 times faster. Then the following python DP solution takes 3.6 seconds on my PC so, it would take ~23.5 seconds on the remote PC. So if the remote time limit 15 seconds, the following solution must be minimum ~ 1.56 times faster in order to pass. Ufff....

import time

try:
    # just to see the Python 2.5 + psyco speed - 17 times faster than Python 2.7 !!!
    import psyco
    psyco.full()
except:
    pass

def editDistance(s1, s2):
    if s1 == s2: return 0
    if not len(s1):
       return len(s2)
    if not len(s2):
       return len(s1)
    if len(s1) > len(s2):
        s1, s2 = s2, s1
    r1 = range(len(s2) + 1)
    r2 = [0] * len(r1)
    i = 0
    for c1 in s1:
        r2[0] = i + 1
        j = 0
        for c2 in s2:
            if c1 == c2:
                r2[j+1] = r1[j]
            else:
                a1 = r2[j]
                a2 = r1[j]
                a3 = r1[j+1]
                if a1 > a2:
                    if a2 > a3:
                        r2[j+1] = 1 + a3
                    else:
                        r2[j+1] = 1 + a2
                else:
                    if a1 > a3:
                        r2[j+1] = 1 + a3
                    else:
                        r2[j+1] = 1 + a1
            j += 1
        aux = r1; r1 = r2; r2 = aux
        i += 1
    return r1[-1]

if __name__ == "__main__":
    st = time.time()
    t = raw_input()
    for i in range(int(t)):
        a, b = raw_input(), raw_input()
        print editDistance(a, b)
    #print "Time (s): ", time.time()-st

What I can say - It's very very hard or may be impossible to pass that puzzle using Python and DP approach (using java or c++ - peace of cake). Wait, wait - ask you - what about that two guys that passed using python? Ok, the answer is easy - they use something different. What's exactly? Something that I've used for java solution I think. That stuff just blows away the competitors....


Based on your example I would suggest you spend some more time on plain MVC before you try to work with a service layer. Something else to keep in mind is that the requirements of the application you're building determine whether you even need a service layer. In your example you don't. Actually since you're not really retrieving any data, your example doesn't need the model either.

The simplest way to describe the relationship between the controller and the view is that the controller does all the work and then sends data only to the view. The view then takes the data and displays it any which way it wants. This is valuable because it means you can make serious changes to one or the other or both without there being much risk of the changes causing undesired effect. It makes maintaining and expanding code much easier.

In your example you don't really make a clear separation between the view and the controller as far as the actual execution code goes. I would take a hint from MS.Net MVC and make better use of objects to separate the roles and interfaces of each layer properly.

Take this over-simplified example based on what you provided:

class View{}
class ViewData{}
class Controller{}
class ControllerData{}

$cData = new ControllerData();
$cData->event = "add_event";
$cData->a = 2;
$cData->b = 3;
$cObj = new Controller($cData);
$vData = $cObj->getData();   //returns a ViewData object
$vObj = new View($vData);
$vObj->renderView();


PDO prepared statement - binding variable number of values

For this:

// Create an array of '?,' values - one for each id
foreach($deleteRowArray as $addBind) {
    $array[] = '?,';
}

// Remove the last array values comma
end($array);
$array[key($array)] = '?';
reset($array);

// Create the finished query with as many binded values as needed
$sql = 'DELETE FROM dataformset WHERE DataFormSetId IN (' . implode($array) .') LIMIT 3';

I guess the following is the same but much simpler:

$array = array_fill(0, sizeof($deleteRowArray), "?");
$sql = 'DELETE FROM dataformset WHERE DataFormSetId IN (' . implode(", ", $array) .') LIMIT 3';

You don't need to put the separator char into the array, implode can handle it and it doesn't put separator after the last element, so you don't have to remove it.

// Remove the text "FieldId" and bind each ID into a single prepared statement
$deleteRow = preg_replace("/[^0-9,.]/", "", $deleteRow);

I'd be a little bit more defensive here and remove only FieldId from the beginning of the string, not every non-allowed character. It's a sign of an error of the caller if you got a $deleteRow which doesn't start with FieldId. In that case you should indicate it somehow (throw an exception). There is no point to delete rows if the data is definitely invalid. (The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas: Dead Programs Tell No Lies.)


It's a good habit to end each statement with an explicit semicolon.

The innermost query q generates one row for each recent user.  Since you have no interest in individual users, and only want counts and sums, you can collapse the two innermost queries q and r — both poorly named, by the way — into one.  Use COUNT() for counting.

The lastActiveDays filtering is being done inefficiently:

where datediff(d, LastAccessDate, getdate()) <= @lastActiveDays

To accomplish that, the server would have to run datediff() on every single row in the Users table.  Instead, you should calculate the cutoff date just once:

where LastAccessDate >= cast(dateadd(day, -@lastActiveDays, getdate()) as Date)

(The cast truncates the result to midnight.)

I prefer to use Common Table Expressions for readability.  Since you are not running a correlated subquery, a top-down layout is better than nesting.

The UserStats CTE below is roughly equivalent to subquery q.  I've deferred the … / @target… divisions for readability and rearranged the columns in a more logical order.  It could be written as just one SELECT, but I think that splitting it up with a CTE makes it easier to understand.

declare @target_20k float;
declare @target_10k float;
declare @target_3k float;
declare @target_2k float;

set @target_20k = 3.0;
set @target_10k = 10.0;
set @target_3k = 80.0;
set @target_2k = 120.0;

declare @lastActiveDays int;
set @lastActiveDays = 60;

with UserStats as (
  select
      count(case when Reputation >= 20000 then 1 else null end) [20KUsersCount],
      count(case when Reputation >= 10000 then 1 else null end) [10KUsersCount],
      count(case when Reputation >=  3000 then 1 else null end) [3KUsersCount],
      count(case when Reputation >=  2000 then 1 else null end) [2KUsersCount],
      count(case when Reputation >=   150 then 1 else null end) [AvidUsersCount],
      count(Id) [UsersCount],
      sum(case when Reputation >= 150 then Reputation else 0 end) [AvidUsersRep],
      sum(Reputation) [TotalSiteRep]
    from Users
    where LastAccessDate >= cast(dateadd(day, -@lastActiveDays, getdate()) as Date)
)
select
    round([20KUsersCount] / @target_20k, 2) [20K],
    round([10KUsersCount] / @target_10k, 2) [10K],
    round([3KUsersCount]  / @target_3k,  2) [3K],
    round([2KUsersCount]  / @target_2k,  2) [2K],
    [TotalSiteRep],
    [UsersCount],
    round([TotalSiteRep] / cast([UsersCount] as float), 2) [AvgRep],
    [AvidUsersRep],
    round([AvidUsersRep] / cast([TotalSiteRep] as float), 2) [%AvidRep],
    [AvidUsersCount],
    round([AvidUsersCount] / cast([UsersCount] as float), 2) [%AvidUsers],
    round([AvidUsersRep] / cast(AvidUsersCount as float), 2) [AvgAvidRep]
  from UserStats;


Sql Server: Getting the highest value based on two uniqueidentifiers - possible to avoid union?

Why don't you use IN instead of the JOIN?

SELECT MAX([Sequence])
FROM [RiscProfileType]
WHERE 1 = 1
   AND [Active] = 1
   AND [ID] IN (@riscProfileTypeId1, @riscProfileTypeId2)

Or rethink the logic:

SELECT [ID]
FROM [RiscProfileType]
WHERE 1 = 1
   AND [Active] = 1
   AND [ID] IN (@riscProfileTypeId1, @riscProfileTypeId2)
ORDER BY [Sequence] DESC
LIMIT 1


At a quick look:

Your code is vulnerable to SQL Injection: assume the user wants to hurt you, so always parse superglobals $_GET and $_POST

https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
To check if variable have values:

// good practice
if (isset($userName, $userPass))
// bad practice
if ($userName && $userPass )

More important:

  Don't reinvent the wheel unless you plan on learning more about wheels.

A simple search on google for PHP login system will give you a limitless number of examples from where you can learn how to build a proper system:

http://www.phpeasystep.com/workshopview.php?id=6


Makefile for CGI program using SQLite library

First impressions
This is clear and easy to read, and follows conventions well.

Use more built-ins
You can use more of Make's built-in rules.  For example, this rule can be omitted entirely:
sqlfuncgi.o: sqlfuncgi.c
    $(CC) -o $@ $^ -c $(CFLAGS)

If you add $(SQLITEDIR) to the VPATH, the sqlite3.o rule becomes simply
sqlite3.o: CFLAGS += -Os

And the link rule can use the built-in LINK.c variable:
sqlfun.cgi: sqlfuncgi.o sqlite3.o
    $(LINK.c) -o $@ $^  $(LDLIBS)

Special targets
Good use of .PHONY.  We probably also want .DELETE_ON_ERROR to ensure that if any command fails, its partially-written outputs don't hang around and appear to be made

Portability improvement
We can use Make's predefined $(RM) in place of rm -f.


There is no way to get the items contained in a Directory once they have been added.

Your base class defines:

public abstract Directory AddDirectory(string name);
public abstract void AddFile(string name, IFileBuilder fileBuilder);
public abstract void Remove(FileSystemItem item);

These methods only make sense for a Directory. The fact that one of your two subclasses has to throw an InvalidOperationException for each of these abstract methods is an indication that they should not be part of the base class. Even worse, someone who has a reference to a FileSystemItem has no way of knowing if calling one of these methods is safe without explicitly checking the actual type of the instance.

Note: Iterating over the contents of a directory (mentioned above) is another operation that only makes sense for a Directory. It would be best to let FileSystemItem define the core properties, but not try to force the aspects that don't work for all of the subclasses.

This will likely mean you will need to keep a directories contents in two separate collections. You can still expose a function that allows iterating over all of the items, but someone using that call would not have access the Directory specific methods.

FileSystemItem defines _rootPath as a member variable, but it is not used.

I prefer to have member variables at the top of the class. This way, someone reading the class for the first time, will know what variables are available to methods before seeing a method trying to use one.

I prefer to always use curly brackets for if statements and loops. It makes things less error prone when you have to edit the code later.


Insert a node at a specific position in a Linked List

This is how I would have done it:

Node* InsertNth(Node *head, int data, int position)
{
    // Use a sentinel as this leads to simpler code
    // and no need to test for the empty list case.
    Node sentinel{-1, head};

    // Find the position we want to insert in.
    // Note: If there are less than `position` elements then
    //       the new element will be added to the end.
    Node* current = &sentinel;
    for(; position != 0 && current->next;--position, current = current->next)
    {}

    // Create the new Node and insert it into the chain.
    Node* newNode = new Node{data, current->next};
    current->next = newNode;

    // Update head.
    // In the case of null list or inserting at position 0
    // this will do something. Otherwise this is a no-op.
    head = sentinel.next;

    return newNode;
}

Notes:

Make notes of assumptions you have made in the comments.
I like the for() expression over the while() expression.
It expresses my intent more clearly (ie that I am just chaining along the list).
No need to dynamically create the sentinel. By declaring it on the stack. It works better.
I have assumed node has a reasonable constructor to make the code cleaner.


Possible optimizations for calculating squared euclidean distance

You can decrease Python's overhead by parsing the args tuple and creating the return value manually.

Try changing these portions of your code:

/* Parse the input tuple */
if (!PyArg_ParseTuple(args, "OO", &x_obj, &y_obj))
    return NULL;

<< code snipped >>

/* Build the output tuple */
PyObject *ret = Py_BuildValue("d", value);
return ret;

to this (untested) code:

/* Parse the input tuple manually */
if (PyTuple_GET_SIZE(args) != 2) {
    PyErr_SetString(PyExc_TypeError, "requires 2 arguments");
    return NULL;
}

x_obj = PyTuple_GET_ITEM(args, 0);
y_obj = PyTuple_GET_ITEM(args, 1);

<< code snipped >>

/* Return double as Python float */
return PyFloat_FromDouble(value);

Updates

Without any changes, your code takes ~340ns on my computer. Changing the argument processing and how the return value is created decreases the running time to ~295ns. Replacing pow() with multiplication didn't change the performance with my compiler (GCC 4.8.2). Changing the exponent to a non-integral value significantly increased the running time so I assume constant integer exponents are optimized by the compiler.

Next, I simplified the conversion of the numpy arrays by checking that the objects passed are numpy arrays. This avoids creating new objects. I also assumed that the data type is a "float64". Extra checks could be added if needed. With these changes, the running time is ~220ns. Code is below:

static PyObject *euclidean_euclidean(PyObject *self, PyObject *args)
{
    PyObject *x_obj, *y_obj;

    if (PyTuple_GET_SIZE(args) != 2) {
        PyErr_SetString(PyExc_TypeError, "requires 2 arguments");
        return NULL;
    }

    x_obj = PyTuple_GET_ITEM(args, 0);
    y_obj = PyTuple_GET_ITEM(args, 1);

    if (!PyArray_Check(x_obj) || !PyArray_Check(y_obj)) {
        PyErr_SetString(PyExc_TypeError, "requires array arguments");
        return NULL;
    }

    /* Get pointers to the data as C-types. */
    double *x    = (double*)PyArray_DATA(x_obj);
    double *y    = (double*)PyArray_DATA(y_obj);

    double value = euclidean(x, y);

    if (value < 0.0) {
        PyErr_SetString(PyExc_RuntimeError,
                    "Euclidean returned an impossible value.");
        return NULL;
    }

    /* Build the output tuple */
    return PyFloat_FromDouble(value);
}

If I remove the call to euclidean(), the running time is ~75ns. If I remove all the the argument parsing and just return the value 0.0, the running time is ~72ns. I did a few more tests to confirm running times and Python's overhead is consistently ~75ns and the euclidean() function has running time of ~150ns.


You are passing the stack vector by value, which means that on each call to pick, you will incur O(n) time to copy the vectors. You need to pass by reference or const reference.

See my answer here to another question with the same problem:
https://codereview.stackexchange.com/a/144084/36120


Reading a textfile and calling a class with each text file line

public static T[] CopySubArray<T>(this T[] source, int length, int offset = 0)
{
    T[] result = new T[length];
    while (--length >= 0)
    {
        if (source.Length > offset + length)
        {
            result[length] = source[offset + length];
        }
    }

    return result;
}

I wonder why did you write this method? You can replace it with Array.Copy that, strangely enough, you already use in another place and even the exact same overload:

Array.Copy(hash, 0, result, 0, 4);

Signature:

public static void Copy(
    Array sourceArray,
    int sourceIndex,
    Array destinationArray,
    int destinationIndex,
    int length
)

public static string GenerateHash(string email, byte[] passwordAesKey)

This method should only generate a hash and not an encoded string. Encoding the hash is a responsibility for a different method.

ToBase64

Likewise is this method doing too much. It not only creates a base64 string but also replaces some characters. This should moved to a new method like CleanUpBase64String or whatever it does. It can be private but this kind of custom processing should be encapsulated.

Basically this is how it should look like:

public static byte[] GenerateHash(string email, byte[] passwordAesKey)
{
    ..
}

public static string GenerateHashBase64String(string email, byte[] passwordAesKey)
{
    var hash = GenerateHash(email, passwordAesKey);
    return ToEncodedBase64(hash);
}

public static string ToEncodedBase64(this byte[] data)
{
    var base64String = Convert.ToBase64String(data)
    return CleanUpBase64String(base64String);
}

private static string CleanUpBase64String(string value)
{
    ...
}


"Can a list of meetings all be scheduled in a conference room?"

Like knut suggested, a simple solution would be to sort the meetings by start time and for each check if it conflicts with the next.

E.g. given a list of meetings:

conflict = meetings.sort_by(&:start_time).each_cons(2).any? do |a, b|
  a.end_time > b.start_time
end

No need to model a conference room, or raise exceptions; conflict will indicate if the meetings overlap or not.

If the question involved a list of pre-scheduled meetings, and having to check if a new meeting would fit, it'd be a different story. You could use something like this, but the question doesn't call for it.

As for the rest of your code, a few things stood out to me:

does_not_overlap? is a bit odd

it's a negative assertion, rather than overlaps?
why not pass in a Meeting instance instead of start and end times?
and it's got a syntax error (hanging ||)

ConferenceRoom should use the attr_accessor you created or at least @meetings – not self.meetings.
You raise which, yes, is a sort of output, but it's a bit much. All the question needs is a boolean answer.


Finding max z-index featuring in the current page

While I understand you're looking for a snippet that works well on an underlying page you have no control over, any solution for such a problem would technically be a hack.

Your best bet, though certainly not a fool-proof solution, is to just use a very large or perhaps the maximum possible z-index (supposedly 2147483647, though certainly not standardised - I'd just go with something like 10000000) on your element.


I'm going to ignore the non-coded class.  I'm not sure why you'd include both of these.

With that said, here are some things I noticed about the coded class.

Rather than init(simpleName:simpleType:), why don't we expand on our super class's init and also accept the arguments our super class's init takes:

init(texture: SKTexture?, color: UIColor, size: CGSize, name: String, type: Double) {
    self.simpleName = name
    self.simpleType = type
    super.init(texture: texture, color: color, size: size)
}

Then, if we want an initializer that takes just some of these values and uses defaults for the rest, we should make convenience initializers:

convenience init(name: String, type: Double) {
    self.init(texture: nil, color: UIColor.whiteColor(), size: CGSizeMake(10.0, 10.0), name: name, type: type)
}

And we probably should override any of SKNode's constructors which we intend to keep available:

override convenience init(texture: SKTexture?, color: UIColor, size: CGSize) {
    self.init(texture: texture, color: color, size: size, name: "", type: 0.0)
}

Ultimately, the point is, all of our initialization logic should go in as few constructors as possible.  All of our other constructors should call these few designated constructors.


There is a subtle difference between == and CompareTo: the latter is current-culture-aware (or you can pass another one in), the former is not.

However, as Ben points out in the comments, the official recommendation is to use Equals instead of CompareTo outside of sorting operations.

Your devs might also be coming from a Java background where == and equals are a bit more complicated and may very well produce different results. This isn't a concern in C#, so for the vast, vast majority of your equality checks the == will be more than sufficient.


I suppose you can use .reversed() or  .asReversed() to reverse the list of coefficients and iterate over it, without working with the indices:

coefficients.asReversed().forEach {
    result = (result * x) + it
}

Also, you can use the functional idiom of fold/reduce, and replace iteration with folding the list (here, .foldRight(...) is used to fold the collection from its end):

val x = 3
val result = coefficients.foldRight(0) { it, acc -> it + acc * x }


I would write an extension method to do parsing of input string. so it should not be inside  your query method.
I have declared a class named SearchCriteria to encapsulate all data member you want t o query.

this is just a first set of refactoring which should be included.

public class SearchCriteria
{
    public Type EntityType { get; set; }

    public string SubEntityName { get; set; }

    public int EntityId { get; set; }

}

public static class ParseExtension
{
    public static SearchCriteria Parse(this string query)
    {
        string[] parts = query.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        var entityName = parts[0];
        var id = int.Parse(parts[1]);
        var subEntityName = parts[2];

        return new SearchCriteria
        {
            EntityType = GetTypeFromEntityName(entityName),
            EntityId = id,
            SubEntityName = subEntityName
        };
    }

    private static Type GetTypeFromEntityName(string entityName)
    {
        Type entityType = null;
        switch (entityName)
        {
            case "Person":
                entityType = typeof(Person);
                break;
            case "Job":
                entityType = typeof(Job);
                break;
        }
        return entityType;
    }
}

public List<dynamic> LoadEntitiesByQuery(SearchCriteria query)
{
    Type entityType = query.EntityType;

    var tempObj = db.Set(entityType)
                    .AsQueryable()
                    .Where(string.Format("ID == {0}", query.EntityId))
                    .FirstOrDefault();

    var propertyInfo = tempObj.GetType().GetProperty(query.SubEntityName);

    List<dynamic> objects;

    if (propertyInfo.PropertyType.IsGenericType)
        objects = ((IEnumerable<dynamic>)propertyInfo.GetValue(tempObj, null)).ToList();
    else
    {
        var tr = propertyInfo.GetValue(tempObj, null);
        objects = new List<dynamic>();
        objects.Add(tr);
    }

    return objects;
}


Vectors assignations and operations in a loop and parallelization with OpenMP

The only thing worth commenting on is the identifier names could be more meaningful.

Short identifiers are harder to find when maintaining the code (more false positives).
Short identifiers make it hard to put meaning to the identifier.


First, let's go over some problems in your original query:

SELECT MAX(l.id) AS highestID, l.nid, n.status
..............
GROUP BY l.nid

... if there's more than one n.status for a given l.nid, you get a "random" row, decided by the optimizer (and not controllable by you).  I'm presuming that you only have one row here (we'll exploit this in a bit).

(SELECT end_time
 FROM mbl
 WHERE id = (SELECT MAX(id)
             FROM mbl
             WHERE nid = l.nid
             GROUP BY nid)) <= NOW()

I'm presuming that id is still some sort of autogenerated value.  The problem is, outside of some very specific contexts, the only thing a db-generated id should be used for is its uniqueness.  Especially in situations where rows may be updated, max/min/ordering by ids rapidly becomes irrelevant.  You seem to be attempting to make sure the most-recently-added row has an end_time value in the past - if you have some sort of inserted_at or similar timestamp, that would be a better column to use.  It would also be helpful to know why you're looking for the greatest id in this case.  (However, as I don't know the other columns in you table, I'm stuck with it for the moment).

It turns out that your statement can be reduced to this:

SELECT Most_Recent.highestId, Most_Recent.nid, Node.status
FROM (SELECT nid, MAX(id) AS highestId
      FROM Mbl
      GROUP BY nid) Most_Recent
JOIN Node
  ON Node.nid = Most_Recent.nid
JOIN Mbl
  ON Mbl.nid = Most_Recent.nid
     AND Mbl.id = Most_Recent.highestId
     AND Mbl.end_time <= NOW()

.... which not only eliminates a table reference, but your original version had issues with potential RBAR (row-by-agonizing-row)/Cartesian product plans.  Note that we're still required to join to Mbl twice, with the second time being solely to make sure that the most-recent row also has an end_time value in the past (this can't be done in the subquery, because that would collect the most-recent-id of rows with end_time in the past)


Handling rejected HTTP responses with status 401

I'd actually go a bit further than janos. He is perfectly right in that by repeatedly checking rejection.status, you're repeating yourself in code. Repeatedly checking the variable against multiple values makes this a perfect candidate for a switch statement:

responseError: function(rejection) {
    if (rejection.status === 401) {
        switch (rejection.config.url) {
            case "user":
                console.log("Check");
                break;
            case "l18n/fr_FR.json":
            case "l18n/nl_NL.json":
            case "l18n/de_DE.json":
            case "l18n/es_ES.json":
            case "l18n/en_US.json":
                console.log("Check2");
                break;
            default:
                $location.path('/login');
                break;
        }
    }

    return $q.reject(rejection);
}


C Garbage Heap aka simplest memory management tool

Interesting concept, I'm going to guess that C is not your first programming language, and your first language did not require explicit memory management.

The code is pretty good, but here are some things to consider:

A Good Programming Practice
In most of the if statements and loops the code in the question is hard to maintain because it doesn't provide complex statements for each path through the code. A complex statement is a code block encapsulated in the C language by { and }.

An example of a complex statement is:
        {
            STATEMENT;
            STATEMENT;
        }

An example of the code lacking this good programming practice is

void free_garbage_heap(void)
{
    for (int i = 0; i < garbage_heap.len; ++i)
        if (garbage_heap.buffer[i] != NULL)
            free(garbage_heap.buffer[i]);
    free(garbage_heap.buffer);
}

Let's say that someone maintaining the code has to add a statement to the if statement in the loop and they are looking to do it quickly or they come from a programming language that is positional rather than using braces to denote a complex statement. If they add it immediately below the free(garbage_heap.buffer[i]); without adding the braces, not only is the new statement not in the if statement, the new statement isn't even in the for loop.

In languages such as C and C++ the following code is a safer programming practice:

void free_garbage_heap(void)
{
    for (int i = 0; i < garbage_heap.len; ++i)
    {
        if (garbage_heap.buffer[i] != NULL)
        {
            free(garbage_heap.buffer[i]);
        }
    }
    free(garbage_heap.buffer);
}

Where to add a new statement becomes much clearer.

Possible Improvements for the Function init_garbage_heap
The first thing to note in init_garbage_heap() is that there is no error checking after the call to void* malloc(int number_of_bytes_to_allocate). The call to malloc() may fail, and if it does the value returned is NULL. If the code continues to process if malloc() returned an error, then there would be a memory access error in the for loop for garbage_heap.buffer[i] = NULL; that will probably cause the program to crash (exit improperly). In C++ if new() fails it throws an exception, the C programming language does not have exceptions so the test is required.

The second thing to note in the following code is that the cast to (void**) is not necessary in C99 or later versions of C, in the original version of C malloc() return char* and required casting, now that it returns void* it does not.

void init_garbage_heap(void)
{
    int len = 32;
    garbage_heap.len = 0;
    garbage_heap.capacity = len;
    garbage_heap.buffer = (void**)malloc(sizeof(void*)*len);
    for (int i = 0; i < len; ++i)
        garbage_heap.buffer[i] = NULL;
}

The third thing to note is that the type of garbage_heap.buffer can change so it might be better if sizeof(*garbage_heap.buffer) * len was used rather than explicity stating sizeof(void*)*len. That way if the type of buffer changes the code only needs to change where buffer is declared rather than in multiple places.

The for loop to initialize the contents of garbage_heap.buffer to NULL might be replaced with a call to void * memset ( void * ptr, int value, size_t num );:

    memset(garbage_heap.buffer, 0, sizeof(*garbage_heap.buffer) * len);

This may possibly perform better speed wise than the for loop depending on how memset() is written. It is also written in the terms of the rest of the code.

If the call to malloc() is replaced by a call to calloc() neither the for loop or a call to memset() is required because calloc() will set the contents of the memory being returned to NULL.

Possibly improved version of `init_garbage_heap(void):

void init_garbage_heap(void)
{
    int len = 32;

    garbage_heap.len = 0;
    garbage_heap.capacity = len;
    garbage_heap.buffer = calloc(sizeof(*garbage_heap.buffer), len);
    if (!garbage_heap.buffer)
    {
        fprintf(stderr, "Unable to allocate memory for garbage_heap.buffer, exiting program");
        exit(EXIT_FAILURE);
    }
}

It is not clear why len is being assigned 32, it might be better to use a symbolic constant instead of 32. It might also be nice if the user of these routines could set the initial allocation capacity. It would be better if the initial buffer size was larger than 32 to reduce the need for resizing.

Spacing
The code in garbage_heap.c might be more readable if there was vertical spacing inside the functions.


Time and space complexity is usually represented with n and m, so O(check*sample) and O(sample) would be O(nm) and O(n).

For complexity, if m is sample, and n is check, time complexity is actually O(n(n-m)), or \$O(n^2 - m)\$, which I would say is simple O(n). Same with space complexity, as well (this I am not sure about, please correct me if I am incorrect).

Also, you have:

public class AnagaramInBigString {

and:

private static Map<Character, Integer> frequencyMap(String str)
{

One word to describe this: inconsistency. Be consistent. Either have a newline, or don't.

I suggest not have a new line, as it wastes newlines, and doesn't it make it a bit more readable. It also follows Java conventions.

This crazy code:

    if(str.charAt(i) == ' ')
    {
        continue;
    }
    else
    {

        if(source.containsKey(str.charAt(i)))

        {
            source.put(str.charAt(i), source.get(str.charAt(i) + 1));
        }
        else source.put(str.charAt(i), 1);
    }

I can't even follow it. In addition to the above suggestion, always put braces for if, for, and while statements, no matter how long or short the statements are. Result:

    if (str.charAt(i) == ' ') {
        continue;
    } else {
        if (source.containsKey(str.charAt(i))) {
            source.put(str.charAt(i), source.get(str.charAt(i) + 1));
        } else {
            source.put(str.charAt(i), 1);
        }
    }

The continue can be removed by reversing the expression:

    if (str.charAt(i) != ' ') {
        if (source.containsKey(str.charAt(i))) {
            source.put(str.charAt(i), source.get(str.charAt(i) + 1));
        } else {
            source.put(str.charAt(i), 1);
        }
    }

and the put can be simplified with ternary:

    if (str.charAt(i) != ' ') {
        source.put(str.charAt(i), source.containsKey(str.charAt(i)) ?
                source.get(str.charAt(i) + 1) :
                1);
    }

Also consider using JUnit 4 for testing.


Evaluating a math expression given in string format

How does it work?

Seems to be working now. What I can't understand is how :)

Code should be readable and easily understandable by humans as well. You might even be one of the humans that have to work with code that you wrote a year or more ago..

There is a lot going on in the code that I cannot tell why it's there and what its use is.

For example:

 if (operationOnQueue) {
                    operationOnQueue = false;
                    secondNum = s;

                    list.set(list.lastIndexOf(firstNum), eval(firstNum, operator, secondNum));
                    list.remove(list.lastIndexOf(operator));
                    list.remove(list.lastIndexOf(secondNum));
                }

I can read the code and see what it will do, but why? I have no clue.

So either try to explain the why in comments, or re-write the code to be more self-explanatory.

(Btw your code looks a bit like https://en.wikipedia.org/wiki/Shunting-yard_algorithm.)

Try to break big methods into smaller ones

You evaluate does a few things. The while loop in the end seems like a good candidate for a separate method. The second if in the for loop as well.

Don't repeat yourself

There are a few Character.toString(tokens[i]) in the code. It's easier to read if you extract that to a variable, for example String currentToken = Character.toString(tokens[i])

Handling error cases

What if the input is not a correct expression?

For example: 14+54/9+

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.get(ArrayList.java:433)
    at Math.evaluate(Math.java:64)
    at Math.main(Math.java:96)

BTW: for more interesting links / implementations see here:
https://stackoverflow.com/a/114601/461499


Finding a string whose MD5 starts like the digits of π

The algorithm you're using is a brute-force algorithm.  It will require around (24)n hash checks for a match of n digits.  Each additional digit will require an average of 16-1 more time to calculate than the previous one.

The first, and hopefully obvious, step would be to get a better algorithm for a huge speedup - unfortunately, this is non-trivial in this case.

An additional step could be to use a language that is, typically, faster than Python.  You probably want a compiled language like C/C++, or even Java.

Lastly, this is a perfect parallel computing problem.  You have lots of small pieces (i.e. pick some text and hash it) and each is distinct, so they're easy to do in parallel.

Here I've given some improvements for a Python program, brute-force algorithm, singly-threaded.

The most important aspect of the code is how quickly we can create the word and calculate the md5 hash.  I've rewritten your code to not use an infinite loop, but instead loop for a specific number of tries.  This lets us time things using timeit.

from hashlib import md5
from random import choice, shuffle
from string import ascii_lowercase
from timeit import timeit
from itertools import product, islice
from os.path import commonprefix

def find_hash_pi_external(tries):
    n = 1
    for _ in range(tries):
        word = ''.join(choice(ascii_lowercase) for _ in range(20))
        if (str(md5(word.encode('utf-8')).hexdigest()))[:n] == '31415926535897932384626433832795'[0:n]:
            print('n=' + str(n) + ", " + word)
            n = n + 1

Some other comments:

The method hexdigest() returns a string, so you don't need to call str() there.
You can exclude the 0 in a[0:n].
You don't always have to increment n by one - sometimes you've found one that will match more than n characters.

def find_hash_pi_1(tries):
    pi = '31415926535897932384626433832795'
    n = 1
    for _ in range(tries):
        word = ''.join(choice(ascii_lowercase) for _ in range(20))
        hash = md5(word.encode('utf-8')).hexdigest()
        if hash[:n] == pi[:n]:
            n = len(commonprefix([pi, hash])) # note: commonprefix is slow so we only use it if there is a success
            print('n=' + str(n) + ", word=" + word + ", hash=" + hash)
            n = n + 1

The code above calls choice many times to make each word random.  We don't need to do that - instead, we need only different word value in the each step of the loop. It also creates the word as a string, but the md5 module requires bytes.  It is expensive to convert, so we can try to create the word as bytes without the string intermediate.

def find_hash_pi_2(tries):
    pi = '31415926535897932384626433832795'
    n = 1
    letters = bytes(ascii_lowercase, 'utf-8')
    for word in islice(product(letters, repeat=20), tries):
        word = bytes(word)
        hash = md5(word).hexdigest()
        if hash[:n] == pi[:n]:
            n = len(commonprefix([pi, hash])) # note: commonprefix is slow so we only use it if we have a hit
            print('n=' + str(n) + ", word=" + word.decode('utf-8') + ", hash=" + hash)
            n += 1

At this point the profiler is telling me that the built-in method _hashlib.openssl_md5 takes up about 10% of our time.  There is still space to improve, but our brute-force algorithm that uses separate md5() calls will be difficult to improve by much more.

Below I've shown the timeit output for all three solutions

if __name__ == "__main__":
    print(timeit('find_hash_pi_external(2 ** 16)', setup="from __main__ import find_hash_pi_external", number=1))
    print(timeit('find_hash_pi_1(2 ** 16)', setup="from __main__ import find_hash_pi_1", number=1))
    print(timeit('find_hash_pi_2(2 ** 16)', setup="from __main__ import find_hash_pi_2", number=1))

Results:

n=1, iaathglhsnzablgilhim
n=2, vjvcpilnwymbckhubdxl
n=3, gteyvjexqwahhbgasvco
n=4, rhjccvcubaeqfurjbfgi
1.227025089520841
n=1, word=wanforjhvqrpgnbbvlap, hash=3feca550be69a201c6147a0a20dbf338
n=2, word=eulvqycsfrgqhotpqsah, hash=3177a30c82a3b12856def16568d8b155
n=3, word=knmwruvaahghowwsyqyx, hash=3146373e28453b9dc7d1bb9961917dec
n=4, word=qrsgbfrcwrzwlqjgmryp, hash=31414f71ee6ba9516c9d0acb16e67662
1.239360037012343
n=1, word=aaaaaaaaaaaaaaaaaabp, hash=3f6056bb268f4176685134ae56a838da
n=2, word=aaaaaaaaaaaaaaaaaaqt, hash=311468ef9220551699d61e9b70e43aa7
n=4, word=aaaaaaaaaaaaaaaaafml, hash=314125241241d57b8085afe08b50bdf0
0.10168091144473257


Scrape a reddit post submission for comments and save comments to JSON file (revised)

This is much clearer now (hopefully, you also agree).

Some more ideas:

It is sometimes considered cleaner to always define functions before their use.

Some old comments still apply (magic number -6 and some namings), but there may be reasons for not changing that.

Code now almost reached the top of possibilities for non-object-oriented methodology, so I do not think it's worth crossing the line unless desired.

Using module-level or global data is usually frowned upon, because it makes functions to work magically (there are some exceptions of course). In case of module level configuration, one usually need to override the variable (eg, via monkeypatching). It's much easier for the function to accept the context, which may contain configuration. In the code above, load_survey_responses is the only violation I see, again, maybe it is justified. To see specifically what I mean, imaging that you will need to provide fp parameter as a script parameter: it will require changes to the code in several places instead of just providing fp upfront and propagating to further function calls as part of a context.

(Some readers may notice that prepare_survey_update now reminds
Transaction Script pattern, see https://stackoverflow.com/questions/16139941/transaction-script-is-antipattern discussion on it's pros and cons)

Now that code became cleaner, I've noticed the script reads and writes to the same file (now it overwrites the file with each call). It's ok as far as you do not do things concurrently. But it's another story.


The only part that executes slowly would be the for and the nested
  for. Is there possibly a better way that I can code this?

I take you ask us to optimize the nested loops:

The most obvious problem, as @Antonio also noted, is the O(n^2) filtering in the nested fors. Also as he noted, you need some kind of data structure with O(1) Contains method. However since you do not use other fields of from the rows of ModelResults, you only need a HashSet of ["Request ID"]s.

  I can't imagine this is the optimal coding for data table update
  operations, maybe though? Is this a possibility in LINQ (I'm
  completely new to LINQ)?

I take you are asking for a more compact, more LINQy way of updating a collection, in this case a DataTable:

LINQ is a query language and a LINQ query does not modify underlying IEnumerable. (In most cases you would select a modified copy of the underlying IEnumerable, instead.)

However, you can use List.ForEach on the result of such a query, as a more compact replacement of for loop.

Applying two suggestions above, we get:

var collectedRequestIds = new HashSet<string>(
    modelResults.AsEnumerable().Select(row => row["Request ID"].ToString()));

modelData.AsEnumerable()
    .Where(collectedRequestIds.Contains(row => row["Request ID"].ToString())))
    .ToList().ForEach(row => row["Collected"] = "1");