This codes looks pretty good. I have refactored your code to better use some of the nice things that Python provides, and to help illustrate the following points. Refactored code is below.  Changes made include:

1. pep8:

I changed the code to more closely conform to pep8. This is important when sharing code as the consistent style makes it much easier for other programmers to read your code. There are various tools available to assist in making the code pep8 compliant. I use PyCharm which will show pep8 violations right in the editor.

2. Converted Point and Line into namedtuples:

Converting these objects to named tuples makes them immutable.  This allows them to be keys in dicts and too be added to sets.  This has many benefits.

3. Iterate on list of lines, instead of index:

Since the lines are now immutable, they can be added directly to a set, and the index of the line in the list is no longer needed for this.

4. Iterate inner loop only on unconsidered pairs:

Start the inner loop from the current line only, which removes about half of the comparisons.

5. Turn the test data into a structure that can test the results:

In the test data structure, each line is a key to  dict which references the expected output group for that line segment.  This works because the line is now immutable.

6. Test the results using an assert, instead of print:

This allows the programmer to simply look for pass/fail status and not need to examine print output to verify the code is working.

7. (An update from Comments) Pull line_v1 out of inner loop:

Seeded to_merge_in_this_run = {v_line1} with  single element set literal instead instead of an empty set.  This allowed the removal of already_flagged_for_merge.add(v_line1) as unneeded.

Code:

import math
from collections import namedtuple

Point = namedtuple('Point', 'x y')
Line = namedtuple('Line', 'a b')

def find_v_lines_to_merge(v_lines, tolerance):

    """
    Find vertical lines that can be merged (meaning they have the same x,
    there is a tolerance, for example if tolerance = 20 then 2 vertical
    lines spaced for less than 20 pixel on the x axis are considered to
    be merge-able.
        -vLines : list(Lines) : MUST BE VERTICAL LINES ONLY
        -tolerance : (int) : tolerance for detecting similar vertical lines
    """

    to_merge = []
    already_flagged_for_merge = set()
    for i, v_line1 in enumerate(v_lines):
        if v_line1 not in already_flagged_for_merge:
            to_merge_in_this_run = {v_line1}
            for v_line2 in v_lines[i+1:]:
                if math.fabs(v_line1.a.x - v_line2.a.x) < tolerance:
                    already_flagged_for_merge.add(v_line2)
                    to_merge_in_this_run.add(v_line2)
            to_merge.append(to_merge_in_this_run)

    return to_merge

Test Harness:

test_data = dict((
    (Line(Point(1, 7), Point(1, 13)), 'a'),
    (Line(Point(1, 14), Point(1, 27)), 'a'),
    (Line(Point(1, 28), Point(1, 35)), 'a'),
    (Line(Point(50, 1), Point(50, 5)), 'b'),
    (Line(Point(80, 7), Point(80, 13)), 'c'),
    (Line(Point(1, 36), Point(1, 55)), 'a'),
    (Line(Point(50, 6), Point(50, 13)), 'b'),
    (Line(Point(100, 7), Point(100, 13)), 'd'),
    (Line(Point(100, 14), Point(100, 200)), 'd'),
    (Line(Point(100, 201), Point(100, 500)), 'd'),
    (Line(Point(80, 14), Point(80, 200)), 'c'),
    (Line(Point(1000, 7), Point(1000, 13)), 'e'),
))

# get the test data
test_data_list = test_data.keys()

# shuffle it to a random order
from random import shuffle
shuffle(test_data_list)

# merge the lines
merged_lines = find_v_lines_to_merge(test_data_list, 20)

# verify that the merged lines all match as expected
for merged_line in merged_lines:

    # get the set of line names for each segment in this merge
    line_names = set([test_data[segment] for segment in merged_line])

    # assert there is one and only one name
    assert len(line_names) == 1


iterating over the values of a list of ordered dictionaries

yield!

You're way overthinking the problem. Python has yield. This is one of the coolest things in Python (IMHO). When you want to iterate over a container like this:

for d, delem in custom.items():
    for k, v in delem.items():
        for row in v:
            print(row)

You just write a function that looks pretty much exactly like that:

def iter_over_custom(custom):     ## or a better name
    for _, delem in custom.items():
       for _, v in delem.items():
           for row in v:
               yield row

We can even drop the last loop if you have a sufficiently recent version of Python that supports yield from:

def iter_over_custom(custom):     ## or a better name
    for _, delem in custom.items():
       for _, v in delem.items():
           yield from v

Or you don't actually need .items() since you just need the values:

def iter_over_custom(custom):
    for delem in custom.values():
        for v in delem.values():
            yield from v

That's it. No need for a custom class to effectively reimplement the same. The initial loop could them be written as:

for row in iter_over_custom(custom):
    print(row)

Note that if you had your own class, you could write the above in __iter__ too:

class Custom(object):
    ...
    def __iter__(self):
        for delem in self.whatever.values():
            for v in delem.values():
                yield from v
    ...


I'd focus on 3 main things:

don't use time.sleep() to wait for elements on a page. With hardcoded time delays there is a tendency to wait more than actually needed most of the time and less than needed sometimes - not reliable at all. Instead, use Explicit Waits with WebDriverWait class and a set of Expected Conditions
remove the overhead of firing up a separate Chrome instance - collect the links into a list a reuse the same WebDriver instance - you should expect improvements in page load times as well
improve your locators - XPath locators are generally the slowest - use "by id" locators whenever possible; handling class attributes with CSS selectors is more reliable (raw contains() in XPath may generate false positives - it can be a bit better with concat())

In the end, you should have something like this:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def browsing_pages(driver):
    driver.get('https://twitter.com/login')
    wait = WebDriverWait(driver, 10)

    driver.find_element_by_css_selector('form.signin input.email-input').send_keys('username')
    driver.find_element_by_css_selector('form.signin input.js-password-field').send_keys('password')
    driver.find_element_by_css_selector('form.signin button[type=submit]').click()

    view_all = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".view-all a.js-view-all-link")))
    view_all.click()

    # wait for a profile link to become visible
    wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".stream-item-header a.js-user-profile-link")))

    links = [link.get_attribute("href") for link in driver.find_elements_by_css_selector(".stream-item-header a.js-user-profile-link")]
    for link in links:
        scraping_docs(driver, link)

def scraping_docs(driver, item_link):
    driver.get(item_link)

    # gleaning information of each profile holder
    for prof in driver.find_elements_by_css_selector(".route-profile"):
        name = prof.find_element_by_css_selector("h1.ProfileHeaderCard-name a.ProfileHeaderCard-nameLink")
        tweet = prof.find_element_by_css_selector(".ProfileNav-value")

        _, following, follower = prof.find_elements_by_css_selector(".ProfileNav-value")[:3]
        print(name.text, tweet.text, following.text, follower.text)

if __name__ == '__main__':
    driver = webdriver.Chrome()

    try:
        browsing_pages(driver)
    finally:
        driver.quit()

You may also go for a class with the driver instance kept at self.driver, but I think it's pretty much okay to do it this "functional" way considering that you have only two functions. Good read on the subject:

Stop Writing Classes
Start Writing More Classes


Eloquent methods to calculate the average rent of apartments

I am going to have attributes for up to about 10 rooms, that would mean 20 new methods. Have to be a better way to do this?

The only reason you have all these methods in the first place is because it's unclear how to use the average_rent method. If you would just document it properly, you can remove all the other methods that don't actually contain any logic themselves.

I'm unsure what the difference between amount and rent is, but it may make sense to have two methods: getAmount($roomCount) and getAverageRent($roomCount). If both are needed, you could also just query once and save the result in private fields. What you definitely do not want is what you have now, where you add a method for each amount of rooms you expect. That's what method arguments are for.

Security

You are vulnerable to SQL injection. Never put variables into a query directly, always use prepared statements.

Naming

don't shorten variable names, it makes code harder to read. amt should be amount, etc.
getOneRoomAmtAttribute is really hard to read. Someone not familiar with your code will have no idea what it will do. It also draws too much focus to irrelevant words (eg attribute), and less focus to the important parts (amt). Something like getAmount($roomCount) would be better.
it's hard to understand the difference between avgAmount and avgRent from their names. Average amount of what? Money? What's the difference to rent then?
either always use snake_case or always camelCase, but don't mix them.


How to get the indexes of smallest value per row in a DF, as column index and not column name?

df.apply over axis 1 is generally avoid for performance issues. When should I (not) want to use pandas .apply() in my code
1. pd.Index.get_indexer
cols = df.idxmin(axis=1)
idx = df.columns.get_indexer(cols) # return a numpy array
idx_series = pd.Series(idx, index=df.index)
# Here, index=df.index is important when your DataFrame has custom index values

print(idx_series)
0    0
1    1
2    0
3    2
4    2
dtype: int64

2. df.to_numpy and np.ndarray.argmin
idx = df.to_numpy().argmin(axis=1) # returns numpy array
idx_series = pd.Series(idx, index=df.index)
print(idx_series)

0    0
1    1
2    0
3    2
4    2
dtype: int64

Some timeit benchs
from datetime import timedelta
from timeit import timeit

if __name__ == '__main__':

    setup = """
import pandas as pd
import numpy as np
from random import randrange
total = 10000
df = pd.DataFrame({
        'col1': [randrange(10000) for i in range(total)],
        'col2': [randrange(10000) for i in range(total)],
        'col3': [randrange(10000) for i in range(total)],
        'col4': [randrange(10000) for i in range(total)],
        'col5': [randrange(10000) for i in range(total)],
        'col6': [randrange(10000) for i in range(total)],
        'col7': [randrange(10000) for i in range(total)],
    })
    """

    for stmt in ["pd.Series(df.to_numpy().argmin(axis=1), index=df.index)",
                 "pd.Series(df.columns.get_indexer(df.idxmin(axis=1)), index=df.index)",
                 "df.apply(np.argmin, axis=1)"]:
        t = timeit(stmt=stmt, setup=setup, number=20)
        print(f"{str(timedelta(seconds=t)):20s}{stmt}")

# Results
0:00:00.012226      pd.Series(df.to_numpy().argmin(axis=1), index=df.index)
0:00:00.408151      pd.Series(df.columns.get_indexer(df.idxmin(axis=1)), index=df.index)
0:00:23.908125      df.apply(np.argmin, axis=1)


There are a few problems.

You should not read the value from an atom and update it conditional on its value, as in set-my-signal. It's value may have changed in between those two calls. In this case refs instead of atoms may need to be used.
Do not use unbounded recursion as in call-each.

Instead of:

(defn call-each [[proc & rest :as procedures]]
  (if (empty? procedures)
    'done
    (do (proc)
        (call-each rest))))

You can do:

(defn- call-each [procedures]
  (doseq [proc procedures] (proc)))

error is not a clojure function. So you should have implemented in clojure with throw... Just use throw instead. It would read something like: (throw (UnsupportedOperationException. (str "Unknown operation -- WIRE " m) nil)). Or instead of throwing an exception you can return nil. So it would be easier to extend (add new messages by decorating) the make-wire constructor.
Case analysis (cond) on a constant symbols is someone does a lot in Scheme. Clojure maps are more readable though. Also using keywords :get-signal instead of symbols 'get-signal is more conventional in accessing the fields of a map, record, so on..

make-wire would be read something like this, if I wrote it in Clojure:

(defn make-wire []
  (let [signal-value (ref 0)
        action-procedures (ref '())]
    {
     :get-signal (fn [] @signal-value)
     :set-signal (fn [new-value]
                   (dosync
                     (when-not (= @signal-value new-value)
                       (ref-set signal-value new-value)
                       (call-each @action-procedures))))
     :add-action (fn [proc]
                   (dosync
                     (alter action-procedures conj proc)
                     (proc)))
     }))

The point of encapsulation as taught in SICP is that you can combine components independent of their implementation details.

So you might want to define a protocol explicitly for a wire:

(defprotocol Wire
  (get-signal [w])
  (set-signal! [w new-value])
  (add-action! [w action-procedure]))

Then whether you implement it using a record:

(defrecord WireRec [signal-value action-procedures]
  Wire
  (get-signal [_] @signal-value)
  (set-signal! [_ new-value]
    (dosync
      (when-not (= @signal-value new-value)
        (ref-set signal-value new-value)
        (call-each @action-procedures))))
   (add-action! [_ proc]
     (dosync
       (alter action-procedures conj proc)
       (proc))))

(defn make-wire2 []
  (WireRec. (ref 0) (ref '())))

Or a map:

(defn make-wire3 []
  (let [m (ref {
                :signal-value 0
                :action-procedures '()
                })]
  (reify Wire
    (get-signal [_] (:signal-value @m))
    (set-signal! [_ new-value]
          (dosync
            (when-not (= (:signal-value @m) new-value)
              (alter m assoc :signal-value new-value)
              (call-each (:action-procedures @m)))))
    (add-action! [_ proc]
      (dosync
        (alter m update-in [:action-procedures] conj proc)
        (proc))))))

should not matter.


need some guidance for better coding practice

First, lets show how I'd solve this. Of course, I've got a bit more experience with classes and such.
Note that I have left out quite a few checks, e.g. of negative sizes, invalid references and MemoryReferences without references.
package com.stackexchange.codereview;

import java.util.Optional;

public class Memories {

    public static class MemoryReferences implements Comparable<MemoryReferences> {

        private int[] memorySizes;
        private int[] refs;

        public MemoryReferences(int[] list, int ... refs) {
            this.memorySizes = list;
            this.refs = refs;
        }

        public int totalMemory() {
            int total = 0;
            for (int ref : refs) {
                total += memorySizes[ref];
            }
            return total;
        }

        private int refWithMax() {
            int refWithMax = refs[0];
            int max = memorySizes[refWithMax];
            for (int refIndex = 1; refIndex < refs.length; refIndex++) {
                int curRef = refs[refIndex];
                int curValue = memorySizes[curRef];
                if (curValue > max) {
                    refWithMax = curRef;
                    max = curValue;
                }
            }
            return refWithMax;
        }

        @Override
        public int compareTo(MemoryReferences that) {
            int totalCompared = Integer.compare(this.totalMemory(), that.totalMemory());
            if (totalCompared != 0) {
                return totalCompared;
            }

            return Integer.compare(memorySizes[this.refWithMax()], memorySizes[that.refWithMax()]);
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            for (int ref : refs) {
                if (sb.length() != 0) {
                    sb.append(", ");
                }
                sb.append(Integer.toString(ref));
            }

            return sb.toString();
        }
    }

    public static Optional<MemoryReferences> getLocationsWithOptimumMemory(int[] memorySizes, int optimumMemory) {
        Optional<MemoryReferences> optMem = Optional.empty();

        for (int i = 0; i < memorySizes.length; i++) {
            for (int j = i + 1; j < memorySizes.length; j++) {
                MemoryReferences curMem = new MemoryReferences(memorySizes, i, j);

                if (curMem.totalMemory() == optimumMemory) {
                    if (optMem.isEmpty()) {
                        optMem = Optional.of(curMem);
                    } else if (curMem.compareTo(optMem.get()) > 0) {
                        optMem = Optional.of(curMem);
                    }
                }
            }
        }
        return optMem;
    }

    public static void main(String[] args) {
        {
            int optimumMemory = 10;
            int[] memorySizes = new int[] { 6, 3, 8, 1, 1, 4, 9, 2, 9, 7 };

            Optional<MemoryReferences> optMem = getLocationsWithOptimumMemory(memorySizes, optimumMemory);

            if (optMem.isPresent()) {
                System.out.println(optMem.get());
            }
        }
    }
}

The main idea of this class is to get rid of the overly complex code within the loops and if statements.
It uses a little trick by referencing memorySizes (previously list). As it is a reference, it won't actually consume any additional memory. Instead of making it a pair I allowed any number of references as it was actually easier to program it that way.
It's slightly slow because it always calculates the total and such but hey, maybe memorySizes changes dynamically, right? It implements Comparable to look for the best option out there.

Great, that out of the way, let's do the review:
First of all, there is way too little white-space in the code, compare your code with mine, e.g. put spaces between the memory sizes in list.
import com.sun.tools.javac.util.Pair;

That's a Java implementation class. You should never use any classes within com.sun packages unless they have explicitly been indicated as being a public API.
int[] list = new int[]{6,3,8,1,1,4,9,2,9,7};

Please don't call an array list. And always name containers after the elements they contain.
Pair<Integer,Integer> result = new Pair<>(Integer.MIN_VALUE,Integer.MIN_VALUE);

Never use magics to indicate a bad result. Use null if you have to. But now the result will be set to this result if there isn't an optimalMemory. That's not correct, how are you going to check this?
Pair<Integer,Integer> pair = new Pair<>(i,j);

Again with the naming, what does pair mean, and a pair of what? At least call it pairOfReferences or curPairOfReferences. Don't be afraid of longer names, as long as they are functional.
 //this happens only once, when the very first pair that satisfies the condition is found

Great comment, very helpful. However it would be even better if you can code in such a way that such comments are not needed at all (hence my use of Optional in the code above).
int maximumMemoryInResult = Math.max(list[result.fst],list[result.snd]);
int maximumMemoryInPair = Math.max(list[pair.fst],list[pair.snd]);

Here you show a much better control over variable names, great!
else if(maximumMemoryInResult == maximumMemoryInPair){

Do you really need the confusing else if you just did a continue on the previous line?
int minIndexInResult = Math.min(result.fst,result.snd);
int minIndexInPair = Math.min(pair.fst,pair.snd);

Think about this: when will result.snd ever be smaller than result.fst? Same for pair?
        continue;
    }
}//end of condition2

Yeah, that continue is a bit wasted on me, we're at the end anyway.
}// end of main method

I personally dislike end of line comments with a passion. But besides that, loops and if statements should not need them to indicate where they end. You can do that by moving code out of the loop.


Can I adjust this code which displays a table to run faster?

You don't need to redraw the entire table. Try just doing DOM manipulation to reorder the TRs.  I see that you also want to stripe the rows, but you can still do it with DOM manipulation. You should be able to take it from there.

I created a simple example with almost 1000 rows and it runs almost instantaneously. There's some jQuery just so I don't have to worry about cross-browser issues. If you don't use jQuery, most libraries have the functionality I used,or you can just implement $.text on your own http://jsfiddle.net/unffs/2

var table = document.getElementById('tbl');
// Can't call sort on an HTML collection, so copy the contents to an array
var rows = Array.prototype.slice.call(table.rows);
rows.sort(function(a, b) {
    var aVal = $(a).text(), bVal = $(b).text();
    return aVal > bVal ? 1 : (bVal > aVal ? -1 : 0);
});
var tbody = document.getElementById('tbody');
for (var i=0; i < rows.length; i++) {
    tbody.appendChild(rows[i]);
}

That code works for a table like the following

D

A

C

E

F

B

D

Using data to sort instead of HTML

If you have some underlying data for the table, it will be even faster since you won't need to read the DOM (except for an id attribute)

var data  = [
   {id: 1, value: 'C'},
   {id: 2, value: 'B'},
   {id: 3, value: 'D'},
   {id: 4, value: 'A'}
];

And your HTML looks like

C

B

D

A

Here's the code to sort the table

var table = document.getElementById('tbl');
// Can't call sort on an HTML collection, so copy the contents to an array
data.sort(function(a, b) {
    return a.value > b.value ? 1 : (b.value > a.value ? -1 : 0);
});
var tbody = document.getElementById('tbody');
for (var i=0; i < data.length; i++) {
    tbody.appendChild(document.getElementById('row-' + data[i].id));
}


Minimize sum of array by applying specific operation on x carefully chosen elements

You can simplify the code (and maybe accelarate it) by not assigning variables for values that are used once.
spreading the nums array is slow (Math.max), see
also. Math.max with spreading or the faster alternative (Math.max.apply) for a larger array (somewhere between 120.000 - 130.000 elements) will throw a Range Error, so use a loop for it.
reduce is (a lot) slower than a regular loop, so use a
loop to determine the sum
Math.floor can be replaced by a bitwise operator
(it's slightly faster)
Side note: alway use semicolons

The first snippet shows the aforementioned optimizations

const testLongerArray = [...Array(2000)].map((v, i) => i && i*10 || 1);
const testVeryLongArray = [...Array(200000)].map((v, i) => i && i*10 || 1);
console.log(minSum(testLongerArray, 600)); // out 10812701
console.log(minSum(testVeryLongArray, 1600)); // out 197130527201
console.log(minSum([209,400,77], 4)); //out: 31
console.log(minSum([5000,5000,5000,5000,5000,], 4)); //out: 7000

function maxValue(arr) {
  let max = 0;
  let i = arr.length;
  while (i--) {
    max = arr[i] > max && arr[i] || max;
  }
  return max;
};

function minSum(nums, x) {
    if (nums.length === 0) {
        return false;
    }
    const start = performance.now();

    while (x--) {
        // Note: a loop for max is the fastest
        // and for very large arrays spreading and Math.max.apply
        // will throw, so using the loop here
        const max = maxValue(nums);
        const maxIndex = nums.indexOf(max);
        //               ^ use indexOf
        nums[maxIndex] = (max / 10) | 0;
        //               ^ Math.floor replacement
    }

    // replace reduce with a loop
    let len = nums.length;
    let sum = 0;

    while (len--) {
      sum += nums[len];
    }

    return `sum: ${sum}, time: ${(performance.now() - start).toFixed(2)} ms`;
}

Now you don't have to iterate through the whole array. If you sort the input array descending, you can take a subset of the first [x length] elements of the sorted input array and perform the operation on the elements of that subset. Adding up the subset elements and the elements of the original sorted array minus its first x elements should give the desired result.
That's worked out in the second snippet. In both snippets the performance is timed, so you can compare both snippets (especially for the longer arrays).

const testLongerArray = [...Array(2000)].map((v, i) => i && i * 10 || 1);
const testVeryLongArray = [...Array(200000)].map((v, i) => i && i * 10 || 1);
console.log(minSum(testLongerArray, 600)); // out 10812701
console.log(minSum(testVeryLongArray, 1600)); // out 197130527201
console.log(minSum([209, 400, 77], 4)); //out: 31
console.log(minSum([5000, 5000, 5000, 5000, 5000, ], 4)); //out: 7000

function minSum(nums, x) {
  if (nums.length === 0) {
    return false;
  }
  const start = performance.now();
  const operation = v => (v / 10) | 0;
  nums.sort((a, b) => b - a);
  let subset = nums.slice(0, x);
  let sum = 0;
  nums = nums.slice(x);

  while (x--) {
    const maxVal = maxValue(subset);
    subset[subset.indexOf(maxVal)] = operation(maxVal);
  }
  nums = nums.concat(subset);
  x = nums.length;

  while (x--) {
    sum += nums[x];
  }

  return `sum: ${sum}, time: ${(performance.now() - start).toFixed(2)} ms`;
}

function maxValue(arr) {
  let max = 0;
  let i = arr.length;
  while (i--) {
    max = arr[i] > max && arr[i] || max;
  }
  return max;
}


Checking if a given string is in alphabetical order

Sorting is idempotent, sorting an already sorted list leaves it unchanged.

So checking if a list is ordered equals checking if it equals itself when sorted:

def is_sorted_alphabetically(string):
    return string == ''.join(sorted(string))

If you do not want to have a \$O(NlogN)\$ runtime of sorting or you want to implement this yourself without using the sorted built-in, I suggest you avoid recursion and use the all and pairwise helper functions:

def is_sorted(iterable):
    return all(x1 <= x2 for x1, x2 in pairwise(iterable))

This is general and works for any iterable such as string but also lists of numbers or lists of anything of comparable (the type is Iterable[Comparable] -> bool)


Parsing and extracting all IDs from a document (using regex with capture)

Currently, you're extracting (non-greedily) everything appearing between the IDStart= and &IDEnd. Since this is an ID, and generally the IDs are stored in alphanumeric character sets; you can easily replace the .*? with a [a-z0-9]+ pattern. The & of the &IDEnd will take care of limiting your result between those two words alone.

However, if that is not your case, you should still replace the .*? with .+? so that you won't receive results/captures for a string like: IDStart=&IDEnd.

If the first rule applied to your case, then you can also remove the .Trim call from your GetFristCapture function.

NOTE: I assume that GetFristCapture is a typo. If not, you should rename it to GetFirstCapture.

The the GetFristCapture function itself, do not create a temporary variable. Just return from the if block itself:

Public Function GetFristCapture(m As Match) As String
    ' Gets the first group capture "(...)" in a regex match.
    ' Returns empty string if not a match or there is no group capture found
    If m IsNot Nothing AndAlso m.Success AndAlso m.Groups.Count > 1 Then
        ' Note: The first group is the entire match itself,
        ' so Group(1) is what we want, not Group(0)
        return m.Groups(1).Value
    End If
    Return ""
End Function

Note that I removed the nested if block as well. With your condition m.Groups.Count > 1, you're obviously getting Group(0) and Group(1). Just return Group(1) from there.


pull things from lazy source till timeout is reached

A better name for times would be count.
Your two Pull methods are inconsistent:

The first one actually returns a copy of the entire input sequence (ToArray()) while the second one doesn't.
To keep it consistent with the standard LINQ methods the first method should also just enumerate the input sequence rather than making a copy.

The first method can then be rewritten as:

public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, int? count = null)
{
    return (times == null) ? enumerable : enumerable.Take(count.Value);
}

Or if you prefer to create a new enumerator:

public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, int? count = null)
{
    var items = (times == null) ? enumerable : enumerable.Take(count);
    foreach (var item in items)
    {
        yield return item;
    }
}

When i first read this question I assumed the intend was to only wait a maximum time for an item to arrive (i.e. input sequence is possibly blocking). Reading the code however seems that you just want to consume as many items as you can in a given time span (specifically it doesn't deal with blocking input sequences). Assuming the latter is what you wanted then I'd change the code to not use the enumerator interface but stick on a slightly higher level:

public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, TimeSpan timeout, int? count = null)
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();

    var items = (times == null) ? enumerable : enumerable.Take(count.Value);

    foreach (var item in items)
    {
        if (stopwatch.Elapsed >= timeout) { yield break; }
        yield return item;
    }
}


You want to look at str.join
by the last case, len(listVar) is run 4 times, which is very repetitive.  Better to set it to a temporary variable, and check that each time.
Python has some binary convenience  operators for common things like appending.  Instead of listDisp = listDisp + foo use listDisp += foo
instead of calling str() on everything as you build the string, why not call it up front, so it can't be missed somewhere along the way.  Something at the top like stringList = [ str(i) for i in listVar ] will remove the need for all those str() calls sprinkled throughout the code.
Naming:  listVar is a variable.  It doesn't need to have 'var(iable)' in its name.  How about 'inputList'?  Names are important - they're messages to the future (you or whoever reads your code) about what you are/were trying to accomplish.  Similar issue with the name commaCode.
range(len(listVar[:-1])) is the same as range(len(listVar)-1), which is both easier to read, and can take advantage of point 2 and end up written as range(listVarLen-1) which is definitely clearer.

Overall though, for a beginner, not bad!


I'm repeating @RoToRa for the sake putting it in answer form for beta-stats:

Your syntax is fine. Without knowing more of the problem domain, it does seem a little unnecessary.  Why not use callbacks on your $.ajax() call?


Mapping & Sorting Randomly Generated Numbers

Include the right things

You're starting with:

#include <bits/stdc++.h>
using namespace std;

The second line is bad practice; avoid it. Typing std:: is not a burden. The former is definitely unacceptable - that's a compiler-specific file that you don't want to be including. Just include the actual headers you need:

#include <iostream>
#include <algorithm>
#include <vector>

Use algorithms and iterators

Rather than writing your own loop to perform a sum, you could use the standard algorithm for this: std::accumulate:

int sum = std::accumulate(v.begin(), v.end(), 0);

Also they wanted you to use iterators to find the median, which would be:

auto median_it = std::next(
    v.begin(),
    std::distance(v.begin(), v.end()) / 2);

Where's the rest?

There's a lot of text in that question that I don't think you addressed in your code. Looks like we need a std::map or something.


The method names are consistent, but usually camelcase is advocated.
Indentation is inconsistent, but maybe that's from pasting it here?
Variables like usern and userp are bad, why not name and
password or something that's readable?
Why is the window maximised?  The site doesn't look that's necessary
for anything.
Consider having a login method instead of repeating the same code
five times, e.g. login.login("admin", "admin").
Extract common code to a new method.  That is, for four of the five
tests it could just be checkFailedLogin("foo", "bar").
IDs are/should be unique to elements in HTML, so the XPath is way too
complicated, consider just By.id (and By.className and By.name
for that matter).
Also consider returning the expected page from that method so that
it's clear from the code, MainPage main = login.login(...); and have
it raise an exception if the new page doesn't match what was expected
(e.g. we usually have an invisible value unique to each page to
identify it in tests, but there are probably other ways to do that).


Count numbers whose digits are only increasing or decreasing

Here's a version of your list of lists version using list comprehension and no !! and no explicit recursion:

total 0 = 1
total n = sum
  [ sum (init decgn) + sum (tail decgn) - 9
  | decgn <- take n $ iterate (scanl1 (+)) $ replicate 10 1
  ] + 1

This can probably be reduced further because either of us introduced some unneeded numerical operation somewhere.


Duplicated code in web service consumption

I think it is a bad idea to introduce an empty interface to just add an extension method to it. You should think about an interface as a contract and not merely a way to introduce syntax sugar :)

I believe instead of playing with extension methods it is enough to introduce a separate, helper, internal class whose only purpose would be to throw an exception if fault object is null:

    internal class FaultResponseChecker
    {
        internal static void ThrowIfNotNull(Fault fault)
        {
            if (fault != null)
            {
                throw new WhateverException(fault.reasonText);
            }
        }
    }

If you, as I, don't like static methods, then you can use IoC container to inject  IFaultResponseChecker into the constructor of every class.


Observation.

Though you are compiling this with a C++ compiler and using a couple of C++ classes this is still C code. The style is C and does not reflect the standard idioms of C++.

We refer to code written like this as "C with classes".

Exception Safety

When you see code that looks like:

<Create Resource>

<Do Stuff>

<Destroy Resource>

This is not exception safe. If the code in <Do Stuff> throws an exception then <Destroy Resource> will not be executed. Now you think none of this code throws exceptions and Tidy is a C-library so it will not. But I bet Tidy allows you to register callbacks. These callbacks can throw exceptions and eventually you will add one to the code.

Example:

   TidyDoc tdoc = tidyCreate();
   // Stuff
   tidyRelease(tdoc);

The correct way to do this is to use the RAII idiom. This means creating a class where the constructor allocates the resource and the destructor deallocates the resource.

Since the destructor of an object is automatically called when an object goes out of scope (this includes when the stack is unwound by an exception being thrown) this makes resource allocation/deallocation exception safe.

class TidyDocCPP
{
    TidyDoc tdoc;
    public:
        TidyDocCPP() {
            tdoc = tidyCreate();
        }
        ~TidyDocCPP() {
            tidyRelease(tdoc);
        }
        // This is used to convert an object back to the C form
        // so it can be used in the normal C tidy functions.
        operator TidyDoc() const {
            return tdoc;
        }

        // Need to do this to satisfy rule of 5
        // Don't worry about this section yet.
        TidyDocCPP(TidyDocCPP const&)            = delete;
        TidyDocCPP(TidyDocCPP&&)                 = delete;
        TidyDocCPP& operator=(TidyDocCPP const&) = delete;
        TidyDocCPP& operator=(TidyDocCPP&&)      = delete;
};

Now it can be used like this:

{
    TidyDocCPP    doc;
    tidyOptSetInt(doc, TidyIndentContent, yes); // doc is auto converted
}
// doc goes out of scope here.
// This calls the destructor and releases the resource.

Design

You read the input into a string. Then pass this string to tidyit().

The first issue I have with this is that you pass the string by value. This basically makes a copy of the whole string. Given that modern web pages are huge this is a terrible idea. The main page of stackoverflow.com is 250K.

You should pass immutable strings by const reference (this prevents the copy but still allows full read access).

But even reading the data into a string is incorrect. You have a stream of data (the input) you should use Tidy stream reading capabilities.

Rather than using

 tidyParseString(tdoc, a_input.c_str()

You should use:

 tidyParseStdin(doc);

If you want to be more generic:

 tidyParseSource(doc, inputSource);
 // You will need to build a wrapper aournd TidyInputSource
 // http://tidy.sourceforge.net/docs/api/group__IO.html#g86fcc3c86bd63b26a559938bc38d34bb

Vertical Space

Add vertical space to make your code readable. The current way it is all jammed together makes it highly unreadable.

Brace Alignment

Use one of the standard brae alignment strategies. Yours does not match any standard I have seen.

// K&R Style.  Very common
if () {
}

// Allman.     Very common
if ()
{
}

What you are using seems to be a mix of K&R and Ratliff Style

// Ratliff     Very uncommon
if () {
    }

I have never seen it outside this wikipedia page: https://en.wikipedia.org/wiki/Indent_style

Pick one and use it consistently.


A simple improvement to improve performance by reducing the number of reallocs is to start with a decently sized buffer and when it fills up, grow it by a multiple of the size. For example, you could double the size when it fills up.

Of course this approach is less efficient memory wise, but in order to mitigate that, we can multiply by a smaller multiple (like 1.5x) and/or start with a smaller base size. If you don't care much about memory, you can up the multiple and up the base amount.

For truly enormous files, you will want to chunk your data and process it by chunk instead trying to load it into memory all at once. Another possibility is to just process it as it comes in via an on-line algorithm.

On a side note, it seems like you are reimplementing getline()'s functionality, so unless you need some special behavior, I'd recommend using that instead.


Your clarification made it a lot clearer what you want. I think you're trying too much to make it all fit on two lines and you can make it must more readable by splitting it out a little.

Following straightforward logic (really just translating your description) I came to this which works for all 4 tests (note that argument 10 is an integer, not a double).

public bool AreEqual(string stringValue, object objectValue)
{
  if (objectValue is string)
  {
      double parsedValue;
      if (double.TryParse(objectValue.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out parsedValue))
      {
          return Math.Abs(double.Parse(stringValue, CultureInfo.InvariantCulture) - parsedValue) < 0.00000001;
      }

      return stringValue == objectValue as string;
  }

  if (objectValue is double)
  {
      return double.Parse(stringValue, CultureInfo.InvariantCulture) == objectValue as double?;
  }

  throw new ArgumentException("The object must either be a string or a double");
}

Note that you can also use a direct cast instead of as since it is guaranteed to be a possible cast, but I like to read as myself (the performance impact is minimal and not relevant in our scenario).

Note that I also use double.Parse instead of double.TryParse because from your description I can assume it is either a double or a string. If it isn't, I'm throwing an exception anyway at the end so I don't feel compelled to use TryParse.

I have made changes that take care of the added test cases which you specified later. Alongside that it also takes care of the culture-specific notation (dot vs comma) and floating point errors.

It's more lengthy than your solution but it is also more robust code and a lot easier to digest.

This takes care of the following testcases:

AreEqual("a", "a") // true
AreEqual("a", "b") // false
AreEqual("10", 10.0) // true
AreEqual("11", 10.0) // false
AreEqual("11", "11.0") // true
AreEqual("11", "11.5") // false
AreEqual("11.0", "11") // true


Splitting a string on delimiter outside of quotes while returning item-by-item

You can simplify your logic a bit.  Once in a quote you don't need to check for anything until you either at the end of the string or find another quote.

I also didn't use the ExtendedStringBuilder since I don't have that code and just used the StringBuilder class

From limited testing it returns the same as your function and from using Stopwatch class building a string of 10,000,000 random char it's a bit faster but nothing that couldn't be attributed to noise.

First I would create another method to just read ahead.  It makes it easier to see if we equal the delimiter passed in

private static IEnumerable<char> ReadNext(string str, int currentPosition, int count)
{
    for (var i = 0; i < count; i++)
    {
        if (currentPosition + i >= str.Length)
        {
            yield break;
        }
        else
        {
            yield return str[currentPosition + i];
        }
    }
}

I switch the for loop into a while so I can mess with the counter.  While you can change a counter in a for loop I generally frown on that as a developer I would not normally expect that.  With a while loop I would

public static IEnumerable<string> QuotedSplit2(string s, string delim)
{
    const char quote = '\"';

    var sb = new StringBuilder(s.Length);
    var counter = 0;
    while (counter < s.Length)
    {
        // if starts with delmiter if so read ahead to see if matches
        if (delim[0] == s[counter] &&
            delim.SequenceEqual(ReadNext(s, counter, delim.Length)))
        {
            yield return sb.ToString();
            sb.Clear();
            counter = counter + delim.Length; // Move the counter past the delimiter
        }
        // if we hit a quote read until we hit another quote or end of string
        else if (s[counter] == quote)
        {
            sb.Append(s[counter++]);
            while (counter < s.Length && s[counter] != quote)
            {
                sb.Append(s[counter++]);
            }
            // if not end of string then we hit a quote add the quote
            if (counter < s.Length)
            {
                sb.Append(s[counter++]);
            }
        }
        else
        {
            sb.Append(s[counter++]);
        }
    }

    if (sb.Length > 0)
    {
        yield return sb.ToString();
    }
}

SequenceEqual isn't known to be fast but unless you have a large string you using as a delimiter I wouldn't worry about it.  If you do, then it might be worth changing the IEnumerable<char> into a string using String.Concat and comparing the string from String.Concat directly to the delim variable.

Test

static void Main(string[] args)
{
    var random = new Random();
    var str = String.Concat(Enumerable.Range(1, 10000000).Select(_ => (char) random.Next(32, 122)));
    var timer = new Stopwatch();
    timer.Start();
    var result2 = QuotedSplit2(str, "1\\").ToArray();
    timer.Stop();
    Console.WriteLine(timer.ElapsedMilliseconds);
    timer.Reset();

    timer.Start();
    var result = QuotedSplit(str, "1\\").ToArray();
    timer.Stop();
    Console.WriteLine(timer.ElapsedMilliseconds);
    timer.Reset();

    Console.WriteLine(result2.SequenceEqual(result));
    Console.WriteLine(result2.Length);

    Console.ReadLine();
}


There is Err object, that contains information about run-time errors:
https://msdn.microsoft.com/en-us/library/ka13cy19(v=vs.90).aspx

Err.Number represens error code, if no error Err.Number = 0

You can use this approach in your function:

On Error Resume Next
Set wb = .Workbooks.Open(sPath, False, True)
If Err.Number = 0 then
    wb.close
    CanBeOpen = true
else
    CanBeOpen = false
end if


Mockable clock meeting std::chrono TrivialClock requirement and interface

While I think the underlying idea is quite nice, the actual implementation and design has some issues.
Wrong Abstraction Level
Let's start with the less obvious one: How would you actually use Clock or BaseClock with std::chrono::high_resolution_clock or std::chrono::system_clock?
The simplest approach would be something akin to this:
struct HighResClock : BaseClock {
    time_point now() override { return std::chrono::high_resolution_clock::now(); }
};

It seems so clean, so simple, and so easy. Except that it doesn't compile! That's because std::chrono::high_resolution_clock::time_point is not the same as BaseClock::time_point (and cannot easily be converted, if at all possible).
But: Do we actually need time_points in the public interface?
The only reason to expose time_point values is to extract time differences between them. But that only matters if arbitrary time_points are to be compared.

Technically, the time_point could be stored in some form. However, for many clocks, like std::chrono::steady_clock or std::chrono::high_resolution_clock, the epoch from when the clock are measuring their time offset can change between different executions of the same program (e.g. because the computer got rebooted).
This makes storing time_points, especially those not obtained from std::chrono::system_clock, rather useless. In that case, you'll likely need a calendar library (or similar) to get points of time in a storable format.

But in most cases, a simple Timer abstraction can fulfill all clock needs (comparing some time_points with some relation). A simple Timer interface could look like this:
struct timer {
    // choose an appropriate duration type
    using duration = std::chrono::duration<double>;

    virtual ~timer() = default;

    virtual void start() = 0;
    virtual duration stop() = 0;
    virtual duration tick() = 0; // to obtain multiple measurements from the same baseline
};

class steady_timer : public timer {
    using clock = std::chrono::steady_clock;
    using time_point = clock::time_point;

    time_point start_time;
    bool running;

public:
    steady_timer() = default;

    void start() override
    {
        start_time = clock::now();
        running = true;
    }

    duration tick() override
    {
        return duration(clock::now() - start_time);
    }

    duration stop() override
    {
        auto elapsed = tick();
        running = false;
        return elapsed;
    }
};

Now the only exposed part of the interface is the duration. And it is easily extensible to other time sources (e.g. Win32 QueryPerformanceCounter) or mockable.
Singleton
I really don't like the Clock singleton. Yes, it is easy to just ask a global clock. Yes, it is also easy to screw all code depending on this clock by changing the underlying instance.
For example, a test setting Clock to a mock but not restoring the original clock breaks all other tests that assume the default clock implementation - making test failure dependent on test execution order.
Instead, take a reference or pointer to a timer as parameter. This allows you to pass in a clock where needed, without changing (or corrupting) everyone elses timer.
Rewriting your test case:
class mock_timer : public timer {
    std::vector<duration> measurements;
    int counter = 0;

public:
    mock_timer(std::initializer_list<duration> il) : measurements(il) {}

    void start() override {}

    duration tick() override
    {
        if(counter < measurements.size()) return measurements[counter++];
        return measurements.back();
    }

    duration stop() override
    {
        return measurements.back(); // just example
    }
};

void test_method(){
    using namespace std::literals::chrono_literals;
    mock_timer my_timer{ 10s };

    testClass.methodUsingClock(my_timer);

    // or, more likely:
    testclass inst{my_timer};
    inst.methodUsingClock();

    REQUIRE(testClass.checkTimeout());
}


Should I use module pattern for this notification controller?

Here's a modified version that uses the original singleton declaration.

Description of changes:

Remove all undeclared and thus implicitly global variables.
Remove caching of jQuery selector object (don't see any need for it).
Remove several intermediate variables that are only used once
Add .bind() to event handler so it can use this directly
Change from .done() to .then() to code more closely to the promise standard.

Modified code:

Dnianas.Notification = {
    init: function () {
        this.bindEvents();
    },

    bindEvents: function () {
        $(document).on('click', '#opennotifii', this.markAsRead.bind(this));
    },

    countNotifications: function () {
        var ids = [];

        // Add unread notifications to the ids array.
        $('.boxnotificationsusers').children().find('#boxsendnotifi').each(function () {
            if ($(this).data('read') === 0) {
                ids.push($(this).data('id'));
            }
        });
        return ids;
    },

    markAsRead: function () {
        var self = this;
        var ids = this.countNotifications();

        if (ids.length > 0) {
            $.ajax({
                url: '/notifications/read',
                data: {
                    notifications: ids,
                    _token: token,
                }
            }).then(function (data) {
                self.renderNotificationCount(data);
            });
        }
    },

    renderNotificationCount: function (data) {
        if (data.seen) {
            $('#opennotifii .not_nu1').fadeOut(200);
        }
    }
};

Also, this piece of code looks suspicious:

$('.boxnotificationsusers').children().find('#boxsendnotifi').each(...)

because there should only ever be one '#boxsendnotifi' item in the entire document so if that was the case, you could just do this:

$('#boxsendnotifi').each(...)

or perhaps:

$('.boxnotificationsusers #boxsendnotifi').each(...)

if you want to limit what you find to a particular scope.

Or, perhaps you should just be using a class name if there are potentially multiple matches:

$('.boxnotificationsusers .boxsendnotifi').each(...)


"Spinning wheels" - Animated spinner with SVG and Sass-CSS

I totaly refactored your code (CSS and HTML). I wont address all the modifications and focus on the main ones :

Browser support

The is an issue in firefox when a percentage transform-origin is set on an svg element.If you test your code in FFF, you will see the circles are rotating around the center of the SVG element.
To get around this, I put each circle in a seperate svg element and set the rotation on the svg element itself.

Horizontal and vertical centering

I changed the absolute positionning technique to flexbox as it is more flexible espacialy as you plan on making this responsive.

Responsive

I use the first svg to set the size of the .wrap element. The other ones adapt their size according to the first one with absolute positioning and percentage sizes.

I also tidied up the code

remove positioning on the circle element
removed the z-index as the layers are set with the order of the elements in the markup

html, body { height: 100%; }
body {
  display:flex;
  justify-content:center;
  align-items:center;
  background-color: #efefef;
}
.wrap{
  position:relative;
  width:100%;
  max-width:500px;
  overflow:hidden;
  padding:10% 0;
 }
svg {
  width: 70%;
  height:auto;
  position: absolute;
  animation: turn-circle 5s linear infinite;
  fill: transparent;
  stroke-width: 50;
  stroke-dasharray: 31.5;
}
svg:nth-of-type(1){
  position:static;
  margin:-15% 0 0 -5%;
  stroke: #00aadd;
}
svg:nth-of-type(2) {
  stroke: #00ab02;
  top:0;
  right:-5%;
  animation-duration:4s;
}
svg:nth-of-type(3) {
  stroke: #0053FF;
  top:20%; left:15%;
  animation-duration:3s;
}
@keyframes turn-circle {
  to { -weblit-transform: rotate3d(0,0,1,360deg);
               transform: rotate3d(0,0,1,360deg);}
}
<div class="wrap">
  <svg version="1.1" viewbox="0 0 300 300">
    <circle cx="150" cy="150" r="100" />
  </svg>
  <svg version="1.1" viewbox="0 0 300 300">
    <circle cx="150" cy="150" r="100" />
  </svg>
  <svg version="1.1" viewbox="0 0 300 300">
    <circle cx="150" cy="150" r="100" />
  </svg>
</div>


# path.root is the root of our repo
hashDir = os.path.join(path.root, '_hashes')

Python style guide recommends that global constants are ALL_CAPS

class BaseRule(object):
    '''base object, managing work like checking if results are up to date, and
    calling production rules if they are not'''

    outPath = None

Python style guide recommends that class level constants are ALL_CAPS

    def isUpToDate(self):
        if not os.path.exists(self.outPath):
            return False
        if not os.path.exists(self.hashPath):
            return False
        with open(self.outPath) as f:
            fileHash = self.getOutHas()

You don't use the file you open here, instead you open the file inside getOutHash

        with open(self.hashPath) as f:
            storedHash = f.read().strip()
        return storedHash == fileHash

    def get(self):
        inputPathes = dict([(key, inp.get()) for key, inp in self.inputs.items()])

No need for the square brackets. They make it so that it produces a list. But since you are creating a dictionary there is no need to make a list first.

        if not self.isUpToDate():
            self.func(outPath=self.outPath, **inputPathes)
            self.storeHash()
        return self.outPath

class StableSrc(BaseRule):
    'source file that never change'

    inputs = {}

I know you'll never modify this, but inputs is an object level attribute above, and its clearest if you keep it that way.

    def __init__(self, path):
        self.outPath = path

    def isUpToDate(self):
        return True

def copyTest():
    'test function'

    import shutil

    @rule({'inp' : StableSrc('test.txt')}, 'test2.txt')
    def newTest(inp, outPath):
        print 'copy'
        shutil.copy(inp, outPath)

Usually you've got a small number of possible actions with different inputs/outputs for each use. Your decorator method assumes that each action will be different.

You aren't tracking dependencies amongst the rules. So you can't have some like .swig produces .cpp produces .o which is linked to produce .exe
Creating a class for every rule is odd. It would make more sense to create an object for each rule.
The only thing you've got over makefiles is your use of a hash rather then a timestamp


Lazy man's IEnumerable extension verification method

In my opinion, there shouldn't be a need for this method to begin with. There are very few cases I can think of that would involve passing around a null IEnumerable (or List<T> for that matter). IEnumerable can still express a lack of things to iterate, so you don't often see IEnumerable members returning null. I often see null returned for IEnumerable when the better option would have been to fail or more explicitly inform the caller of an invalid operation. Take this Repository example:

public class Repository<T>
{
    public IEnumerable<T> GetItems()
    {
        bool canConnectToDb = false;
        bool recordsReturned = false;

        // Case 1:
        if(!canConnectToDb)
            return Enumerable.Empty<T>();

        // Case 2:
        if(!canConnectToDb)
            return null;

        // Case 3:
        if(!recordsReturned)
            return null;
    }
}

In "Case 1", the result is misleading. Sure, no records can be returned, but the reason isn't a lack of records to return. Instead, there is an error case that must be handled and an exception should be thrown. In "Case 2", null is being used to show an error state, which is misleading. What was the error? How can I differentiate between a null response, and error handling code using try..catch? In "Case 3", the correct return value would be an empty IEnumerable, not null.

Which leads me to your extension methods...Usually checks like these are trying to cover up  issues rather than failing early and identifying them. For example, lets apply your extension method to refactor the existing Count() extension method:

public static int Count<T>(this IEnumerable<T> iterator)
{
    if(iterator.IsNullOrEmpty())
        return 0;
    else
        // Iterate and count...
}

You just end up perpetrating the issue to create "safe" code that really only hides the issue (that iterator shouldn't have been passed in as null to begin with). The actual implementation probably looks more like:

public static int Count<T>(this IEnumerable<T> iterator)
{
    if(iterator == null)
        throw new ArgumentException("iterator");

    // Iterate and count...
}

This allows it to fail early if it's improperly used, and doesn't make it this methods responsibility to make sure it can always execute given poor conditions.

Lastly, if you do plan on using something like your extension methods, you should know that the extension methods that come with the .NET framework already make performance checks similar to your check if the object is an ICollection. That said, there is no performance check they can do on a custom type that implements IEnumerable, so if you want the count the only option is to iterate through the whole IEnumerable. You don't really need the count though, you just need to know if there is anything being returned, which the Any() extension method does. Instead of iterating through the whole collection, it'll just iterate once and immediately return true if there is anything, which can be a huge performance saver.

A rework of your method:

public static bool IsNullOrEmpty(this IEnumerable iterator)
{
    return iterator == null || !iterator.Any();
}

Maybe I could be convinced by seeing a good application of this extension method, but I can't think of one.

Edit - To address the concern of using another library you can't entirely trust, you have some other options:

1) Use the Facade Pattern to create wrapper objects that do perform to your standards.

2) Treat the issue at the call site to these external libraries and not further into your own code. For example:

var items = BadLibrary.GetItems<T>() ?? Enumerable.Empty<T>();
InternalGoodMethod(items);

public static void InternalGoodMethod(IEnumerable<T> items)
{
    if(items == null)
        throw new ArgumentException("items");

    ....


You can use the function vapply. The help page of ?vapply says:

  vapply is similar to sapply, but has a pre-specified type of return
  value, so it can be safer (and sometimes faster) to use.

You can use

vapply(xz, function(col) col + 100, FUN.VALUE = numeric(nrow(xz))

The argument FUN.VALUE is used to tell the vapply what the function returns. Since all columns are numeric, the function returns a numeric vector of length nrow(xz) for each column of xz. Unfortunately, vapply does not preserve the dates of the xts object.

You can use the following command to generate a new object based on xz and replace all values with the matrix returned by vapply. This is very easy with the following command:

"[<-"(xz, , vapply(xz, function(col) col + 100, FUN.VALUE = numeric(nrow(xz))))

The function "[<-" copies the xz object and replaces all its values.

Alternatively, you can create a new xts object based on the matrix returned by vapply and the time information in your original xts object.

xts(vapply(xz, function(col) col + 100, FUN.VALUE = numeric(nrow(xz))),
    order.by = time(xz))

Now, we test the approaches:

vapFun <- function() "[<-"(xz, , vapply(xz, function(col) col + 100,
                                        FUN.VALUE = numeric(nrow(xz))))

vapFun2 <- function() xts(vapply(xz, function(col) col + 100,
                                 FUN.VALUE = numeric(nrow(xz))),
                          order.by = time(xz))

library(microbenchmark)

op <- microbenchmark(
  app = apFun(),
  sap = sapFun(),
  mXf = mapXf(),
  vap = vapFun(),
  vap2 = vapFun2(),
  times = 1000L)

Unit: microseconds
 expr      min       lq   median       uq        max neval
  app 4066.612 4117.860 4167.324 4270.200 364484.879  1000
  sap 3337.001 3428.798 3463.680 3532.317   4310.336  1000
  mXf 1232.070 1263.531 1275.663 1295.014   2320.361  1000
  vap  984.732 1013.248 1022.726 1035.330 100172.130  1000
 vap2 1326.899 1368.562 1389.672 1428.608 126477.354  1000

As you can see, the approach with vapply and "[<-" is the fastest one.

An important information: if the function you want to apply to each column is a mathematical operation, you can apply it to the whole xts object at once, e.g., xz + 100. This is considerably faster and returns an xts object, i.e., the dates are preserved.

simpleFun <- function() xz + 100

op <- microbenchmark(
  app = apFun(),
  sap = sapFun(),
  mXf = mapXf(),
  vap = vapFun(),
  vap2 = vapFun2(),
  simple = simpleFun(),
  times = 1000L)

Unit: microseconds
   expr      min        lq   median        uq      max neval
    app 4063.972 4119.6995 4145.120 4243.7955 85454.87  1000
    sap 3347.558 3429.6725 3450.778 3515.3745 86508.52  1000
    mXf 1236.142 1267.2030 1276.455 1289.7095 84349.75  1000
    vap  992.792 1017.7425 1024.992 1033.7785 82275.26  1000
   vap2 1336.300 1372.8755 1390.553 1423.9875 83118.79  1000
 simple   92.770   98.4305  101.080  103.9995 81233.70  1000


It seems like you're trying to recreate the functionality of the placeholder attribute that exists in HTML5. For browsers that support it--and that's all modern browsers with the exception of IE9 (I think)--your above code can be replaced with e.g.:

<input type="text" class="contactStyle" placeholder="Your placeholder text">

If you want to also use this functionality in less-modern browsers it'll take some JavaScript, but best not to reinvent the wheel. Several polyfills have been written by other people that let you use the placeholder attribute regardless of browser. There are several listed on this page (do a Ctrl+F for "placeholder").


There isn't much code, so that leaves little to be reviewed. I have not considered the mathematical side of this. This is also a code stub, so when reviewed out of context it is hard to do a good review.

Comment it – As a code stub it is hard to understand what you are trying to achieve, and as such I would problably leave a comment stating what you actually wanted to achieve. Maybe just a reference to "Special Pythagorean triplet, Euler Problem 9", or similar. And possibly some of the justification of your formulas
Do standard indentation – The class and the method is at the same level, which is confusing. Do indent, but keep it a standard width, like 2 or 4 spaces. The same applies for how many lines you use between statements, ending braces, methods. Keep it clean(er)
Keep computation in loop conditions to a minimum – In your case it will most likely be optimised by the compiler, but having computational stuff in the loop conditions, like (num/3 - 1), should be avoided. Do the calculation once in front of the loop, and make it a simple comparision in the loop condition
Take care when using parenthesis – You have some unneccessary parenthesis, and some which is kind of strange, I would have written it: b = num - (500*num) / (num-a) which emphasizes that the denominator and the dividend are calculated before the actual division
Comparing doubles and int is dangerous – In most languages a double variable is usually not checked directly for equality as the imprecision in the storage format could leave to interesting effects. See Spot the defect: rounding, part two. However this might not apply to you as you are mainly interested in a whole number and the decimal parts of it...
Variable naming – Nothing indicates that num is a constant, neither in the naming nor in the declaration (i.e. you could use final). And what does num mean? Is it a number, is it a constant?
Consider using a function – In the problem description it indicates that for other numbers you could find other pythagorean triples, which could be extended into making a method like findPythagoreanTriplet(number) which could either return the first triplet, or a list of triplets. Using a function would allow for extending the code stub into maybe doing something more useful like finding other triplets matching some criteria, or similar
Computation vs presentation – An alternative view on creating a function, is that you could then split the computation from the presentation, which usually is a good thing to do. This also according to the principle of single concern for a method
Jammed if conditions – The last few days I've seen a lot of if(someCondition){, which in my view would like nicer as if (someCondition) {. Having a little space here and there increases readability, asOpposedToNotHavingSpaces...

Do be aware that this code review is making some assumptions, and might be a little overkill for something which you might just have thrown together to solve an immediate problem you had. However, becoming a robust and good programmer, starts by doing it right from the smallest through to the largest projects.


Reimplementation of Underscore _.throttle

Your code isn't quite right, as far as I can tell. In the snippet below, you can compare it to Underscore's version.

function throttle(func, interval){
   var toExecute = true,
       queue = false;
   var result;
   return function doThrottle(){
       var args = Array.prototype.slice.call(arguments);

       if(toExecute){
           toExecute = false;
           queue = false;
           result = func.apply(null, args);
           startTimer(interval);
       } else {
           queue = true;
       }

       function startTimer(interval){
           setTimeout(function(){
               toExecute = true;
               if(queue){
                   result = func.apply(null, args);
               }
            }, interval);
       }

       return result;
   }
}

var count = 0;

function printSomething(elementId, count) {
  document.getElementById(elementId).innerHTML += String(count) + "
";
}

var opThrottledPrint = throttle(printSomething, 2000),
    underscoreThrottledPrint = _.throttle(printSomething, 2000);

function invoke() {
  count++;
  opThrottledPrint("op", count);
  underscoreThrottledPrint("underscore", count);
}

<button type="button" onclick="invoke()">Click me a few times</button>

Printing is throttled by 2 seconds

    OP's code
    Underscore

Three things to note:

If you click twice in row, your throttler does introduce the right delay, but it reuses arguments from the first call when executing the throttled call. So in the snippet's example, your function will cause the same number to be printed twice, despite being called with a new number on each click. I'd consider this a pretty major bug.

The reason for all of this is the curious structure of your code. You set a timeout that's poised to repeat the current call - unless queue is false when the timer runs out. So your code actually creates a sort of "conditional repeater" rather than a throttler.

Again, this is just a strange construction.
If you click twice, and then click a third time as soon as both of the previous calls have executed, the third call executes immediately. In other words, if nothing's "queued" the call is handled immediately, even if it's been less than the delay-time since the most recent invocation.

To attempt some ascii illustration of the behavior of the snippet above:

Time ------->

click . click . . . . . . . . . . . . . . . . . . . click . . . .
  |        \__________________________________        |
  |                      timeout              \       |
print . . . . . . . . . . . . . . . . . . . print . print . . . .
                        ^                         ^
                  Correct delay               No delay!

Again, I'd consider this a major bug since your function is not actually throttling anything in that case.
Returning anything from the throttled function is pointless. Sure, if it executes immediately it will return whatever the wrapped function returns. But if it doesn't execute immediately due to throttling, things get weird.

The wrapper function itself returns immediately; if you set a timeout, it doesn't wait for it to run out. So setting result in the timed function happens long after result has already been returned.

But because result is a closure variable, it's actually worse than a common async mistake: If your call gets delayed/throttled, the previous invocation's return value gets returned.

Like the bug with reusing arguments, this is quite bad if you're expecting to be able to use return values. But, as mentioned, it's impossible to consistently provide return values, when the function may just return before the throttled code has run. So you're better off not returning anything at all.

So with your code, you get:

Delayed repetition instead of actual throttling.
Risk of no throttling at all.
Risk of incorrect return values.

Not really ideal.

I'd do something like this:

function throttle(func, delay) {
  var timer = null,
      queued = null;

  // simple function to introduce a delay
  function delay() {
    timer = setTimeout(resume, delay);
  }

  // end-of-delay handler
  function resume() {
    timer = null;
    if(queued) queued(); // call the queued invocation, if any
    queued = null;
  }

  return function () {
    var args, invocation;

    if(queued) return; // if something's already queued, stop here

    // otherwise get the args...
    args = [].slice.call(arguments);

    // and create a function to apply them
    invocation = function () {
      func.apply(null, args);
      delay(); // make sure any invocation will always cause a delay
    };

    if(!timer) {
      // if there's no timer, invoke immediately
      invocation();
    } else {
      // otherwise enqueue for later
      queued = invocation;
    }
  }
}

You can try it out below. It seems to behave the same as Underscore's.

function throttle(func, interval){
   var toExecute = true,
       queue = false;
   var result;
   return function doThrottle(){
       var args = Array.prototype.slice.call(arguments);

       if(toExecute){
           toExecute = false;
           queue = false;
           result = func.apply(null, args);
           startTimer(interval);
       } else {
           queue = true;
       }

       function startTimer(interval){
           setTimeout(function(){
               toExecute = true;
               if(queue){
                   result = func.apply(null, args);
               }
            }, interval);
       }

       return result;
   }
}

function throttle2(func, delay) {
  var timer = null,
      queued = null;

  function delay() {
    timer = setTimeout(resume, delay);
  }

  function resume() {
    timer = null;
    if(queued) queued();
    queued = null;
  }

  return function () {
    var args, invocation;

    if(queued) return;

    args = [].slice.call(arguments);

    invocation = function () {
      func.apply(null, args);
      delay();
    };

    if(!timer) {
      invocation();
    } else {
      queued = invocation;
    }
  }
}

var count = 0;

function printSomething(elementId, count) {
  document.getElementById(elementId).innerHTML += String(count) + "
";
}

var opThrottledPrint = throttle(printSomething, 2000),
    underscoreThrottledPrint = _.throttle(printSomething, 2000),
    reviewThrottledPrint = _.throttle(printSomething, 2000);

function invoke() {
  count++;
  opThrottledPrint("op", count);
  underscoreThrottledPrint("underscore", count);
  reviewThrottledPrint("review", count);
}

<button type="button" onclick="invoke()">Click me a few times</button>

Printing is throttled by 2 seconds

    OP's code
    Underscore
    Review code


Separate areacode from phone number string with MySQL Database

Assuming my understanding of the question and the data is correct:

  Did I get it right that you want to map your phone number to the area matching the most initial digits? Having 035, 0352, 03522 and 035225 you would expected the location of 035225 for 03522522492?

I would try a SQL-only approach:

SELECT *
FROM Areacodes
WHERE Areacode IN ('032','0352','03522','035225')
ORDER BY CHAR_LENGTH(deliveryAddress_zip) DESC
LIMIT 0,1

So in PHP you now only need to build the IN-clause. Split the phone number in substrings of suitable length (I guess 3-6 digits for Germany).

Without any validation the snipped could look like:

$phone = "03522522492";

$parts = [];
for ($len = 3; $len <= 6; $len++) $parts[] = substr($phone, 0, $len);
$in = "'" . implode("','", $parts) . "'";

echo $in;
//'035','0352','03522','035225'


OpenCL approximation of Pi using vectorized implementation

Addressing question #2, you can move the parallel sum out of the for loop, and only do it once.
Use another double16 variable (initialized to all zeros), accumulate the sum into it during the loop body. Then, once the loop is done, do the parallel sum to initialize work_sum before the last loop that handles that last few elements.


int halfLength

Don't make the user think to much when specifying parameters if this can be avoided. Calculate the target length and let the user specify the length he needs.

If the name should always have an even length then you could check if the given one is odd and if so then add 1.

length = length % 2 == 0 ? length : length + 1;

The loop just divides this by 2:

for (int i = 0; i < length / 2; i++)

I do this because I assumed a longer string is better then a short one so I add 1 to odd lengths but this is actually not necessary as C# will round the number to the next lower int when dividing. This means that 5 / 2 == 2 as far as int division is concerned. If you're ok with shorter strings then you don't need the line with length + 1

char[] vowels = "aeiou".ToCharArray();
char[] consonants = "bcdfghjklmnpqrstvwxyz".ToCharArray();

You don't need to ToCharArray these because strings are already arrays. You can just define two constants:

const string vowels = "aeiou";
const string consonants = "bcdfghjklmnpqrstvwxyz";

List<char> chosenVowels = new List<char>();
List<char> chosenConsonants = new List<char>();

You don't need two lists that you join later. You can use the StringBuilder and create the name right away.

chosenVowels.Add(vowels[r.Next(0, 5)]);
chosenConsonants.Add(consonants[r.Next(0, 21)]);

Don't use magic numbers. Use the constants you have to get the length:

r.Next(0, 5)

You can use the overload that takes just the maxValue.

v.ToString() + c.ToString()

When building longer strings with lot's of concatenations use specialized methods or objects. Concatenating strings with the + operator is the slowest possible way to create a string. The StringBuilder is such an object. Highly optimized for string creation.

With all those optimizations the final result could look like this:

static string GeneratePronounceableName(int length)
{
    const string vowels = "aeiou";
    const string consonants = "bcdfghjklmnpqrstvwxyz";

    var rnd = new Random();
    var name = new StringBuilder();

    length = length % 2 == 0 ? length : length + 1;

    for (var i = 0; i < length / 2; i++)
    {
        name
            .Append(vowels[rnd.Next(vowels.Length)])
            .Append(consonants[rnd.Next(consonants.Length)]);
    }

    return name.ToString();
}

Alternatively to the StringBuilder you could use in this example a char[] array and build the string yourself:

static string GeneratePronounceableName(int length)
{
    const string vowels = "aeiou";
    const string consonants = "bcdfghjklmnpqrstvwxyz";

    var rnd = new Random();

    length = length % 2 == 0 ? length : length + 1;

    var name = new char[length];

    for (var i = 0; i < length; i += 2)
    {
        name[i] = vowels[rnd.Next(vowels.Length)];
        name[i+1] = consonants[rnd.Next(consonants.Length)];
    }

    return new string(name);
}


Function to find the shortest word in an array, where not every element is a string

It seems odd to me that you loop through the array twice, once with every and once with filter. Why not just filter it and check if the filtered array has any elements? Also is there a reason why you used two different methods to check if the elements were strings? One more thing, I would have written the filter method as:

arr = arr.filter(function(e) {
  return typeof e == 'string';
});

If you really want to do this using a single loop you could do something like:

    function findShortestWordAmongMixedElements(arr) {
      return arr.reduce( function(shortest, e) {
        return (typeof e == 'string') && (shortest=='' || e.length < shortest.length) ? e : shortest;
      }, '');
    };

    console.log( findShortestWordAmongMixedElements([
       1, 'longer', 2, 'short', 3, 'longest'
    ]) );


Repair orders query in SQL Server with subselects

Here is a simpler method of your query, which doesn't use a CTE and a bunch of sub-selects.

SELECT
    Plant
    DepartmentName,
    SUM(CASE WHEN NextActivity = 'NEW ORDER REVIEW' THEN ISNULL(Items,0) ELSE 0 END) AS BLindsInQuestion,
    SUM(CASE WHEN LastCompletedActivity = 'LBM INVOICE' OR NextActivity  = 'LBM INVOICE' OR NextActivity ='PLANT ARRIVAL' THEN ISNULL(Items,0) ELSE 0 END) as BlindsReadyToCross
    /*
    etc
    */
FROM
    TotalizedRepairOrders
GROUP BY  Plant ,DepartmentName


I would suggest to use

with open('emails.csv', "rb") as ifile

see here for details: http://www.python.org/dev/peps/pep-0343/
in this case you don't need to do ifile.close at the end

instead of incrementing rownum by yourself, you can use

for row, rownum in enumerate(reader):

I don't see the reason to do this

br['email_add'] = '%s' % (email) #email address

instead of

br['email_add'] = email


Time and space complexity of base conversion code

Much of the following feedback is not really performance-related, but will make the code more easily legible and easily analyzed for the purposes of performance improvement.

Add type hints

b1 and b2 are presumably int, so add : int after their declaration. num_as_string and the function's return value are both str.

Multiple assignment

...has its limited applications, and in this case:

is_neg, num_as_string = True, num_as_string[1:]

there's not really an advantage to combining these two statements. Just do them separately, for legibility.

Exponentiation

You do this:

        base10 += string.hexdigits.index(digit.lower()) * (b1 ** degree)
        degree += 1

But rather than maintaining degree as a number that increases linearly, it's probably a better idea to maintain a number that increases by a multiplicative factor of b1 on every iteration.

Separation of concerns

Fundamentally, convert_base is doing two different things: parsing a string given a particular base into a number, and formatting a number given a particular base into a string. So just make two functions. It's more useful, testable, legible and maintainable.


Extracting matched items from an object which has properties of arrays

Try this code:

function transformObject(data) {
  const values = Object.values(data);
  const keys = Object.keys(data);
  const transposed = values[0].map((col, i) => values.map(row => row[i]));
  return transposed.map(itemArr => keys.reduce((acc, key, i) => ({...acc, [key]: itemArr[i]}), {}));
}

The idea is to transpose the values 2D array and then map it using reduce for each row. The transposed array will look like:

[
  ["1", "foo", 20, "pluto"],
  ["2", "bar", 30, "mars"],
  ...
]

This piece of code keys.reduce((acc, key, i) => ({...acc, [key]: itemArr[i]}), {}) is simply zips two arrays: keys and the row from transposed array.

function transformObject(data) {
  const values = Object.values(data);
  const keys = Object.keys(data);
  const transposed = values[0].map((col, i) => values.map(row => row[i]));
  return transposed.map(itemArr => keys.reduce((acc, key, i) => ({...acc, [key]: itemArr[i]}), {}));
}

console.log(transformObject({
  "id": ["1", "2", "3"],
  "name": ["foo", "bar", "baz"],
  "age": [20, 30, 40 ],
  "location": ["pluto", "mars", "jupiter"],
}));


Your code will work eventually, but this series converges very very slowly.  In fact, as you can read on Wolfram's web site:

  ... this sum converges so slowly that 300 terms are not sufficient to calculate pi correctly to two decimal places!

Here's a better way to do it which implements this function:

$$ \pi = \sum_{k=0}^\infty \frac{4(-1)^k}{2k+1} \bigg(\frac{1}{2^{2k+1}} + \frac{1}{3^{2k+1}}\bigg)$$

(function(){
  PI=0;
  n=-4;
  for(k=0;k<100;k++) {
    z = 2*k+1;
    n *= -1;
    PI += n/z*(Math.pow(2, -z) + Math.pow(3, -z));
  }
  console.log(PI);
})();


You probably reached the maximum speed you can achieve with the API you are using. You could try the following extra hints, just in case they’re not the default values:

g2dBuffer.setRenderingHint(RenderingHints.KEY_RENDERING,
                                              RenderingHints.VALUE_RENDER_SPEED);
g2dBuffer.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                              RenderingHints.VALUE_ANTIALIAS_OFF);
g2dBuffer.setRenderingHint(RenderingHints.KEY_DITHERING,
                                              RenderingHints.VALUE_DITHER_DISABLE);
g2dBuffer.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
                                              RenderingHints.VALUE_COLOR_RENDER_SPEED);

Also, try replacing TYPE_INT_RGB with TYPE_INT_BGR or TYPE_3BYTE_BGR to experiment with how efficiently the Java graphics libraries do their byte packing. But it’s pretty unlikely you’ll see a noticeable difference.


First things first - if you're going to need to maintain SQL, it's best to make it easy to maintain first: start with proper indentation and vertical spacing:

SELECT
     product_table.ProductCode as product_code
    ,SUM(grouped_store_orders_table.po_qty*product_pack_sizes.pack_size_qty) AS order_qty
FROM
    (SELECT
         orders_table.barcode
        ,orders_table.po_qty
        ,orders_table.po_ordering_unit
     FROM orders_table
     GROUP BY
         orders_table.barcode,
         orders_table.po_ordering_unit) AS grouped_store_orders_table
LEFT JOIN product_table
    ON product_table.barcode = grouped_store_orders_table.barcode
LEFT JOIN product_pack_sizes
    ON grouped_store_orders_table.barcode = product_pack_sizes.barcode
    AND grouped_store_orders_table.po_ordering_unit = product_pack_sizes.unit_of_measure
WHERE product_table.Category IN (2,3,4,5)
    AND product_table.DistroRoute <> 'C'
GROUP BY
    product_table.ProductCode;

Aliases should make your life easier - I like dropping the AS keyword since it's not really needed, and I like to keep my aliases short/concise - and don't use them where they're not needed.

You're performing these joins, and then filtering product categories with a where clause; I don't know your data, but you may be able to significantly reduce the amount of rows involved in the join by filtering products first:

LEFT JOIN (SELECT * FROM product_table
           WHERE Category IN (2,3,4,5) AND DistroRoute <> 'C') products
    ON products.barcode = source.barcode


I am trying to write the simplest to understand code possible, each function has documentation and examples and I tried to use the best style possible.

The individual methods are simple and easy to understand.
The docstrings are especially great, they are fantastic help for the reader.

To improve further, try to zoom out. Take a step back and look at the outline of the code, like some advanced editors fold the function bodies and show only the method signatures:

def cycle_get(lst,index): ...

def cycle_increment_index(index,lst): ...

def shift(letter,value): ...

def convert_key_to_numbers(key): ...

def encrypt(text,key,reverse_operation=False): ...

def decrypt(text,key): ...

I don't know if you see it, but things look less clear at this level:

It's hard to guess what cycle_get(lst,index) and cycle_increment_index(index,lst) would do. Also, curiously, although both seem to take a list and a number parameter, the order of parameters is reversed. This will be difficult to remember for users of the class.
shift(letter,value) could be clearer: the method shifts letter by some number, but value is too generic, so it doesn't help guessing that.
convert_key_to_numbers(key) comes quite close, but it would help to be more specific and call "numbers" to "indexes" instead.
encrypt(text,key,reverse_operation=False) is clear, but the reverse_operation parameter is a bit too long. But the biggest problem is that the parameter doesn't really make sense: what is a reverse operation of encrypt? The reverse of "encrypt" should be "decrypt", which shouldn't belong in this method
decrypt(text,key) is clear :-)

I would recommend this alternative outline:

def get_circular_index(lst, index):
    return index % len(lst)

def get_circular_item(lst, index):
    return lst[get_circular_index(lst, index)]

def get_next_index(lst, index):
    return get_circular_index(lst, index + 1)

def shift_letter_by(letter, num):
    # ...

def convert_key_to_indexes(key):
    return [ALPHABET.find(i) for i in key]

def cycle_text(text, key, reverse=False):
    # ...

def encrypt(text, key):
    return cycle_text(text, key)

def decrypt(text, key):
    return cycle_text(text, key, reverse=True)

For the shorter ones I included the implementation too.
I made some other changes too:

The original cycle_get and cycle_increment_index were sharing the "index cycling logic". I moved that part of the logic in one place, a new get_circular_index function.
encrypt is just as clear now as decrypt, and these methods shouldn't call each other, but the common purpose method cycle_text.
As suggested above, the methods and method parameters are renamed to what I hope would be more natural, and the method parameters are consistently ordered.

The CHARACTERS_THAT_MUST_REMAIN_THE_SAME variable is long.
I tried to find a better name for it,
but it was too hard.
When it's too hard to name something,
it's often the sign that there's a better way.
In this case, is this variable really necessary?
It seems the intention is to put characters in it that you don't want to encrypt / decrypt.
Its purpose seems sort of the opposite of the ALPHABET variable.
But it's not really the opposite of that.
And it could be, and it would be simpler.
So instead of the condition if char in CHARACTERS_THAT_MUST_REMAIN_THE_SAME: ...,
how about using if char not in ALPHABET: ... ?

With this in mind, I would recommend this implementation for cycle_text:

def cycle_text(text, key, reverse=False):
    text = text.lower()
    indexes = convert_key_to_indexes(key)
    index_of_key = 0
    result = ""
    for char in text:
        if char not in ALPHABET:
            result += char
        else:
            if not reverse:
                result += shift_letter_by(char, indexes[index_of_key])
            else:
                result += shift_letter_by(char, - indexes[index_of_key])
            index_of_key = get_next_index(indexes, index_of_key)
    return result

Another improvement I slipped in here is not reassigning to the key parameter inside the method body, as it was in the original code.

Why all the redundant parentheses in the return statements?

return(lst[new_index])
return(index)
# ...

All these could be simply like this without parentheses:

return lst[new_index]
return index
# ...

You should follow PEP8, the official coding style guide of Python.

For example, instead of this:

return encrypt(text,key,reverse_operation=True)

You should put a space after every comma separating a list of parameters, like this:

return encrypt(text, key, reverse_operation=True)

And put 2 empty lines before function declarations (before every def).
This rule is only for functions in the global namespace,
for functions inside classes 1 empty line is enough.


There's not a huge amount to review here.

It looks like the Apple code is intended to be a drop-in replacement for OpenSSL, so you could probably just rename to match, rather than creating a new name:

#ifdef  __APPLE__
#define COMMON_DIGEST_FOR_OPENSSL
#include <CommonCrypto/CommonDigest.h>
#define SHA1 CC_SHA1
#else
#include <openssl/sha.h>
#endif

Whichever approach you take, don't forget to #undef the macro when you've finished using it (definitely before the end of the header), to avoid polluting the macro namespace for others.

I would prefer src.data() to &src[0] as the idiomatic way to access a string's characters as an array of char.

And I think I prefer sizeof src to SHA_DIGEST_LENGTH in the first overload, so that the connection is clear.

Is there any reason that src can't be a reference to const in both versions?

inline void thorSHA1(ThorSHADigestStore& dest, ThorSHADigestStore const& src)
{
    THOR_SHA1(src, sizeof src, dest);
}

inline void thorSHA1(ThorSHADigestStore& dest, std::string const& src)
{
    auto const src_bytes = reinterpret_cast<const unsigned char*>(src.data());
    THOR_SHA1(src_bytes, src.length(), dest);
}

I withhold comment on the suitability of SHA-1 for this purpose, as that appears to be something you're stuck with.


Some tips:

Know your PEP8, format your code appropriately.
Learn string formatting - and know the differences between 3.6 and earlier.
Your errMsg and Exception process seem like you expect an error but what error are you expecting? Might want to specify which error you're expecting from your edge cases. ValueError? AttributeError? Also, you shouldn't perform equality statements against None.
if (count == None or not isinstance(count, list) or len(count) != 2) has redundant brackets

And use a proper test harness instead of writing your own. Here is your code with your expect function removed and using pytest:

import pytest

def coin_sum(coins, total):
    # tabulation way
    arr = [1] + [0] * total
    for coin in coins:
        for i in range(coin, total + 1):
            arr[i] += arr[i - coin]
    return 0 if total == 0 else arr[total]

def test01():
    example = coin_sum([1, 2, 3], 4)
    assert example == 4

def test02():
    example = coin_sum([2, 5, 3, 6], 10)
    assert example == 5

def test03():
    example = coin_sum([2], 10)
    assert example == 1

def test04():
    example = coin_sum([7, 15], 20)
    assert example == 0

def test05():
    example = coin_sum(
            [78, 10, 4, 22, 44, 31, 60, 62, 95, 37, 28, 11, 17, 67, 33, 3, 65, 9, 26, 52, 25, 69, 41, 57, 93, 70, 96, 5,
             97, 48, 50, 27, 6, 77, 1, 55, 45, 14, 72, 87, 8, 71, 15, 59], 100)
    assert example == 3850949

And here are the results:

C:\PycharmProjects\codereview\tests>pytest test_tt.py
======================== test session starts ========================
platform win32 -- Python 3.7.0, pytest-3.6.2, py-1.5.4, pluggy-0.6.0
rootdir: C:\PycharmProjects\codereview\tests, inifile:
plugins: cov-2.5.1, celery-4.2.0
collected 5 items

test_tt.py .....                                               [100%]

===================== 5 passed in 0.13 seconds ======================

Hope this helps!


Wrapper class for adding elements to HashSet

Why build your own implementation when you can use the features available in the Java standard libraries?

IdentityHashMap gives you all the features you need, and a Java Stream/collector will allow you to extract the map easily from your collection....

Collection<Test> tests = .....
Map<Test,Test> uniques = tests.stream().collect(Collectors.toMap(
     t -> t,
     t -> t,
     (t,u) -> t,
     IdentityHashMap::new))

Now, if the size of the uniques is the same as the tests, you're good. The uniques Map is an IdentityHashMap where the key values are all identical instances (using ==). It supports a null key/value so that should be fine too.