Fast way to calculate source response using Green's function

Performance wise

In general:

You use numpy, but you write it almost like in fortran. Python with numpy is good for scientific programing and computing as long as you don't do many loops

read this first A beginners guide to using Python for performance computing
if you really need to do tight loops than use
cython.
But most of the time you can avoid that by expressing the loop as some functional operation on the whole array

most numpy functions can operator on whole array in one pass, use it.

always prefer y[:]=np.sqrt(x[:]) and avoid

          `for i in xrange(N):
                y[i]=np.sqrt(x[i])`

operation like dot,convolve,einsum,ufunc.reduce are very potent to express most sciencetific algorithms in more abstract way
use advanced array slicing

you can express most inner if by boolen mask arrays or integer index array

e.g. f[ f>15.0 ] = 15.0 clamp all elements in array f which are >15.0 to 15.0; you can also store the boolean mask mask = (f>15.0) and than use it like f[mask]+=g[mask]. This way you can express branching as fully functional programs/expressions with arrays.
Do not construct new np.array (np.zeros, np.ones etc.) too often (i.e. inside tight loops). Optimal performance is obtained if you prepare all arrays you need at the beggining. Avoid frequent conversion between list and array

To address your code example in particular:

Green's functions are basically convolutions. I'm pretty sure you can express it using e.g. scipy.ndimage.filters.convolve
if your convolution kernel is large (i.e. pixels interact more than with few neighbors) than it is often much faster to do it in Fourier space (convolution transforms as multiplication) and using np.fftn with O(nlog(N)) cost.
cannot def gw(xx, yy, tt, mm, nn, ss): operate on the whole array,
rather than individual numbers?
if denom < 0: can be expressed using boolean mask array like mask = denom >0; denom[mask] = np.sqrt(denom[maks])
Never do this if you can:

  for k in range (Nt):
     for j in range (Ny):
        for i in range (Nx):

the operations seems to be possible to rewrite that operate on the whole x,y space at once

This is how you do convolution-like operations in numpy (from here)

           # The actual iteration
           u[1:-1, 1:-1] = ((u[0:-2, 1:-1] + u[2:, 1:-1])*dy2 +
                            (u[1:-1,0:-2] + u[1:-1, 2:])*dx2)*dnr_inv

this is so horrible:

green = np.array([gw(x[i],y[j],t[k],i_grid,j_grid,k_grid) for k_grid in t for j_grid in y for i_grid in x])

list comprehesion is relatively fast, but still much slower than numpy array operations (which are implemented in C).
do not create temporary list and convert it to temporary array, you loose lot time doing that.
why you cannot just prealocate Green[Nx,Ny,:] and  Gauss[Nx,Ny,:] and use it as a whole?


JavaScript to parse json that can be, string, object and array

Personally I would have written the function as below.
One thing that stood out that I noticed is that you are not returning anything in the catch statement of your try. So there is a certain 'ambiguity' as to what the function will return.

Here is my reasoning for the code style below:

I expect the invoker to provide me with the JSON string that needs to data extracted from it, so that I can perform some immediate input validation. If the input is falsey I will return an empty string.
I check whether the parsed result is an instance of an array (undefined or null will not pass this check)
If it is an instance of an array I will check whether it is an array of objects, otherwise I will assume it is a string. I map these entries, and join them with a comma and return the result
if the type is of an object (and not array since we already checked for that), I will return the name property of that object.

Feel free to wrap this in a try'catch but make sure you return something on the catch. I assume the invoker is expecting a string back.

function parseAuthor(authorString){
  if(!authorString){
    return '';
  }

  const authorObj = JSON.parse(authorString);

  if (typeof authorObj === 'string') {
    return authorObj;
  }

  if (authorObj instanceof Array) {
    entries = authorObj.map((a) => {
      if(typeof a === 'object' && a.name){
        return a.name;
      } else {
        return a;
      }
    });

    return entries.join(',');
  }

  if (typeof authorObj === 'object' && authorObj.name) {
    return authorObj.name;
  }

  return '';
}


Looks like decent code. I think you only got downvoted (once) because you alluded to how you wanted to use this function as part of a (gasp!) program — and then of course twice more because they saw you'd already been downvoted once. That's just how this site works. :)

The biggest problem with your code is that it uses the identifiers iterable, iterable_attr, iterator_attr, iterators, it, and iter, all with different meanings. That's too many its!

iterable_attr and iterator_attr could be called more like ITER_ATTR and NEXT_ATTR, because (A) the capitalization indicates that they're constants, and (B) the names indicate the values they hold. However, this is right up there with THREE = 3. When you see yourself giving symbolic names to global constants, it's time to DRY up your code:

    if hasattr(it, '__iter__'):
        string = isinstance(it, str)
        if not ((string and len(it) <= 1) or
                (string and not strings)):
            it = iter(it)
    if hasattr(it, '__next__'):
        iterators.append(it)
        iterators = iterators[:depth]

Actually, that logical expression buried in the middle there looks like it could stand some De Morgan's Laws. Also, string is a bad name for a boolean! Name your booleans after predicates: in this case, is_string would do. But let's see if we need it at all.

        is_string = isinstance(it, str)
        if not ((is_string and len(it) <= 1) or (is_string and not strings)):
            it = iter(it)

De Morgan 1:

        is_string = isinstance(it, str)
        if not(is_string and len(it) <= 1) and not(is_string and not strings):
            it = iter(it)

De Morgan 2:

        isnt_string = not isinstance(it, str)
        if (isnt_string or len(it) > 1) and (isnt_string or strings):
            it = iter(it)

Distributive law:

        isnt_string = not isinstance(it, str)
        if isnt_string or (strings and len(it) > 1):
            it = iter(it)

Refactor to emphasize the one special case we're trying to express:

        if (not hasattr(it, '__iter__')) or (len(it) <= 1):
            pass  # can't explode this guy
        elif (not strings) and isinstance(it, str):
            pass  # we're not exploding strings
        else:
            it = iter(it)  # explode it

The next two lines

        iterators.append(it)
        iterators = iterators[:depth]

look suspicious. We're appending to the array and then immediately truncating it? Couldn't we do that in some cleaner way?

By the way, that *, in the signature must be a Python-3-ism; I'm not sure what it means. In Python 2 you'd just omit it and it would still do what you wanted.

Your exhausted = object() ... if it is exhausted idiom is neat, if maybe a bit too cute. It beats catching the exception from next(iterators[-1]), anyway.

Unit tests (especially for depth=...) would go a long way here.


4 different implementations of modulo with fully defined behavior

Is there an error somewhere, something that i missed? Is there an error somewhere, something that i missed?

Certainly have most of main street covered.
if (y == -1) return 0; is a nice trick.
y = abs(y); fails 32-bit math when int is 16-bit.  Could use labs() or conditional code or an if() block.  (Only real portability bug I see.)
Pedantic: int32_t is an optional type.  It is missing and code fails to compile on select (dinosaur) machines that do not have 32-bit unpadded 2's complement.
Pedantic: On a select (unicorn) machine where int is 64-bit and int32_t exist, promotions occur.  I do not see a problem though.
Pedantic: Usage of x ^ y obliges 2's complement encoding for correct functionality which is the case with intN_t here , but not all integers on all machines.

Adding a test harness would help.

Can it be simplified?

A shot at simplifying Euclidean division (result is always non-negative).  Similar code may apply to the other 2 cases.
// Substitute `int` for `int32_t`, `long long`, etc.
int modulo_Euclidean(int x, int y) {
  if (y == 0) exit(-1);
  if (y == -1) return 0;
  int m = x % y;
  if (m < 0) {
    m = (y < 0) ? m - y : m + y;
  }
  return m;
}

Does not require intN_t math*, 2's complement, no padding, range constants, nor extended math.

It would be interesting to see if 64-bit math was really slower or a reasonable candidate.
int32_t mod_rem_or_euc(int32_t x, int32_t y) {
  if (y == 0) exit(-1);
  int_fast64_t m = (int_fast64_t) x % y;
  ...
}

* intN_t types are 2's complement, no padding.


LaTeX table generator - file in argument list

Argument checking
You test that the user has specified exactly one input file, but if not, then print the misleading message

Error loading file.

You would be better with a usage message, such as
std::cerr << "Usage: " << argv[0] << " filename" << std::endl;

Well done for correctly using cerr for such messages.
File checking
Here, you use the supplied filename, but never check whether fin was successfully opened.  You probably want:
std::ifstream fin(argv[1],std::ios::in);
if (!fin) {
    std::cerr << argv[1] << ": not readable" << std::endl;
    return 1;
}

Similarly for fout:
std::ofstream fout("latex.txt", std::ios::out);
if (!fin) {
    std::cerr << "latex.txt" << ": not writeable" << std::endl;
    return 1;
}

The reading loop also doesn't check for errors, and it has the while (!eof()) antipattern.  This should be something more like (untested):
std::string line;
while (getline(fin, line)) {
    std::vector<double> v;
    std::istringstream nums(line);
    double x;
    while (nums >> x) {
        v.push_back(x);
    }
    if (!nums.eof()) {
        std::cerr << argv[1] << ": parse error" << std::endl;
    }
    matrix.push_back(v);
    row++;
}
if (!fin) {
    std::cerr << argv[1] << ": reading failed" << std::endl;
    return 1;
}

At the very end of the program, check the fail bit of fout:
fout << "\\end{tabular}\n";
fout << "\\end{center}";
return !fout;

Input values checking
If there were no values, you might want to fail before starting to write the output:
const auto rows = matrix.size();
if (rows == 0) {
    std::cerr << argv[1] << ": empty" << std::endl;
    return 1;
}

I'm not sure whether the input needs to be rectangular (i.e. all rows have the same number of columns).  If so, test it:
const auto cols = matrix[0].size();
for (auto i = cols/cols;  i < matrix.size();  ++i) {
    if (matrix[i].size() != cols) {
        std::cerr << argv[1] << ":" << (i+1)
                  << ": line has " << matrix[i].size() << " columns, expected " << cols << std::endl;
        return 1;
    }
}

That cols/cols is just a shorter way to write (std::vector<double>::size_type)1.
Overall approach
You probably don't want to be typing column headings each time you update the data file, so you're most likely to redirect stdin from a file (and you may well want to automate with Make or similar).  I'd suggest that you accept two filename arguments - column headings first, one per line; numeric data second.  That way, you can use the number of lines of the first file as the expected column count when reading the data file (and you could error early when reading a non-conforming line).
Reading the column names first gives you another potential advantage: you could transform the input to output line by line, rather than having to store all lines to the end.  This makes the program a much better pipeline player, and is a good practice when the inputs might be very large.
You might consider simply writing the output to standard out, rather than opening latex.txt; that gives you more flexibility in how you use it.  You'd have to not prompt for the headings then, though!
My version
I've only compiled this, not run it.  In particular, I may well have bad logic in reading the double values from the line string, as I don't normally read whole lines and then parse them.  I've made a couple of other changes, such as reducing scope of temporary variables, closing fin as soon as we've finished reading, and sprinkling const fairy-dust where I can.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

int main(int argc, char* argv[])
{
    if (argc!=2) {
        std::cerr << "Usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }

    std::ifstream fin(argv[1], std::ios::in);
    if (!fin) {
        std::cerr << argv[1] << ": not readable" << std::endl;
        return 1;
    }

    std::vector< std::vector<double> > matrix;

    // Read input values into matrix
    {
        std::string line;
        while (getline(fin, line)) {
            std::vector<double> v;
            std::istringstream nums(line);
            double x;
            while (nums >> x) {
                v.push_back(x);
            }
            if (!nums) {
                std::cerr << argv[1] << ": parse error" << std::endl;
            }
            matrix.push_back(v);
        }
    }
    if (!fin) {
        std::cerr << argv[1] << ": reading failed" << std::endl;
        return 1;
    }
    fin.close();

    // Test that input isn't empty
    const auto rows = matrix.size();
    if (rows == 0) {
        std::cerr << argv[1] << ": empty" << std::endl;
        return 1;
    }
    // Test that input is rectangular
    const auto cols = matrix[0].size();
    for (auto i = cols/cols;  i < matrix.size();  ++i) {
        if (matrix[i].size() != cols) {
            std::cerr << argv[1] << ":" << (i+1)
                      << ": line has " << matrix[i].size() << " columns; expected " << cols << std::endl;
            return 1;
        }
    }

    auto const& outfile = "latex.txt";
    std::ofstream fout(outfile, std::ios::out);
    if (!fin) {
        std::cerr << outfile << ": not writeable" << std::endl;
        return 1;
    }

    static auto const col_sep = " & ";
    static auto const row_sep = " \\\\\n\\hline\n";

    fout << "\\begin{center}\n\\begin{tabular}{";
    for (int i=0;  i<col;  ++i) {
        fout << "|c";
    }
    fout << "|}\n"
         << "\\hline\n";

    // Ask for col titles:
    for (int i=0;  i<cols;  ++i) {
        std::cout << "Enter the title of column " << i+1 << ", as TeX source:" << std::endl;
        std::string title;
        getline(std::cin,title);
        fout << title
             << (i==cols-1 ? row_sep : col_sep);
    }

    // Write out the values
    for (const auto& v: matrix) {
        for (auto i=0u;  i<cols;  ++i) {
            fout << v[i]
                 << (i==cols-1 ? row_sep : col_sep);
        }
    }

    fout << "\\end{tabular}\n"
         << "\\end{center}";
    fout.close();

    if (!fout) {
        std::cerr << "Failed to write " << outfile << std::endl;
        return 1;
    }

    return 0;
}


1. Review

It's usually more convenient to return a result rather than printing it. Then you can use the result in other computations, for example test cases.
It's not clear what the meaning of the table t is. It would be helpful to have a comment. I think that if \$i ≤ j\$ then t[i][j] gets filled in with the maximum money obtainable by a player who starts with the coins \$v_i, \dots, v_j\$.
There is some trouble in handling edge cases — you need to avoid an invalid lookup in the table t so instead of writing t[i+1][j-1] you have to write:

0 if i+1 > j-1 else t[i+1][j-1]

to avoid trouble in the cases i+1 == n and j == 0. What this suggests is that t would be better implemented as a mapping from pair (i, j) to money, using collections.defaultdict:

from collections import defaultdict
t = defaultdict(int)    # Map from (i,j) to max money on v[i:j+1].

Then you could look up any pair and it would default to zero even if it was out of bounds, like this:

x = t[i + 1, j - 1]
y = t[i + 2, j]
z = t[i, j - 2]
t[i, j] = max(v[i] + min(x, y), v[j] + min(x, z))

In this code:

for gap in xrange(n):
    for i in xrange(n):
        j = i + gap
        if j<n:

you could avoid the test j<n by iterating only over valid values of i:

for gap in xrange(n):
    for i in xrange(n - gap):
        j = i + gap

These lines of code:

x = t[i + 1, j - 1]
y = t[i + 2, j]
z = t[i, j - 2]
t[i, j] = max(v[i] + min(x, y), v[j] + min(x, z))

are looking two steps ahead (the next player chooses the minimum of their options, and the current player chooses the maximum of theirs).

But it is simpler to look only one step ahead, like this:

s = sum(v[i:j+1])
t[i, j] = s - min(t[i + 1, j], t[i, j - 1])

How does this work? Well, s is the sum of all the coins from i to j, so if the next player can win t[i + 1, j] (say), then the current player can win whatever's left.

(This is a standard trick when implementing a minimax algorithm. Instead of having different code for the even (max) and odd (min) players, use the same code for both players and negate the score at each step so that max and min swap roles.)

However, this is inefficient because of the computation of s, which requires iterating over all the coins from i to j. But we can avoid this by precomputing a list of running totals, using itertools.accumulate:

from itertools import accumulate
totals = [0] + list(accumulate(v))

and then the computation of s becomes:

s = totals[j + 1] - totals[i] # sum(v[i:j+1])

2. Revised code

from collections import defaultdict
from itertools import accumulate

def optimal_strategy_game(coins):
    """Return the maximum possible amount of money that can be won by a
    player starting on the given row of coins.
    """
    n = len(coins)
    totals = [0] + list(accumulate(coins)) # Running totals over coins
    money = defaultdict(int) # Map from (i,j) to max money on coins[i:j+1].
    for gap in range(n):
        for i in range(n - gap):
            j = i + gap
            s = totals[j + 1] - totals[i] # s = sum(coins[i:j+1])
            money[i, j] = s - min(money[i + 1, j], money[i, j - 1])
    return money[0, n - 1]

3. Alternative approach

The technique here (of building a table of solutions to sub-problems) is known as dynamic programming. But code that uses dynamic programming can always be rewritten to use recursion to visit the sub-problems and memoization to avoid duplicate work. Sometimes this results in clearer code. In Python 3.2 or later, many functions are easy to memoize using the @functools.lru_cache decorator:

from functools import lru_cache
from itertools import accumulate

def max_money(coins):
    """Return the maximum possible amount of money that can be won by a
    player starting on the given row of coins.
    """
    totals = [0] + list(accumulate(coins)) # Running totals over coins

    @lru_cache(maxsize=None)
    def money(start, stop):
        "Return maximum money that can be won on coins[start:stop]."
        if start >= stop:
            return 0
        else:
            s = totals[stop] - totals[start] # s = sum(coins[start:stop])
            return s - min(money(start + 1, stop), money(start, stop - 1))

    return money(0, len(coins))

(Python 2.7 lacks lru_cache but there's a backport.)


Function to determine what color shirt somebody should wear to a football game depending on what seat they have

I see 2 points where you can work to increase the quality of your code.

simplify some conditions check
get rid of comments

simplify some conditions check

Consider the following code:

/* Case 3: Section is two letters (No numbers) */
else if (section.length == 2 && section.charAt(0) >= 'A' && section.charAt(0) <= 'Z'  &&
       section.charAt(1) >= 'A' && section.charAt(1) <= 'Z') {

I think you could make it shorter with just a regular expression:

else if (section.match(^[A-Z]{2}$)) {

It is not just short and fast to read, but, in this case, it show you what is the "rule" that the string should satisfy.

get rid of comments

Your code is full of comments, and that made it difficult to reed.

Consider that many developer, me included, don't trust the comments and read it just when something weird happened. And in this case too there are very few times the comments helps.

The reason is you should update the comments as you update the code, but this never happened as it is more work and you don't have time.

Compilers or interpeter never care the comments.

The other point is that the developers could read and understand the code, and your effort should put in made the code readable for human beings.

Let me show some examples.

  /* Case 1: Section is a special section */
  if (section.includes("TER") || section.includes("WC") || section.includes("EC")) {

Consider the followhing change. As you can see you don't need the comment any more.

if (isASpecialSection(section)) {

...

function isASpecialSection(section) {
    return section.includes("TER") || section.includes("WC") || section.includes("EC");
}

Another example:

/* Case 2: Section is a single letter (No numbers) */
else if  (section.length === 1) {

Even the condition is short, you should use the same approach, as it is not clear in which case you are here.

Look at the comment, it "lied", because you just check that the string have length 1, not that is only letters. Maybe you don't have the case today, but data could change.

So remove the comment and change the check:

else if (section.match(/^[A-Z]$/)) {

Not all comments are bad, you should avoid those comments that tell what the code does, because you can read the code and so it is a waste of time for the developers that read your code.

Too many comments like in your code make difficult to read the code.
To put all those comments you break the indentation.

Try to make your code more readable by using proper names or functions to encapsulate complex conditions.

Naming is hard and take time, I know, but it pay back.


As your List is instantiated as an ArrayList, the lookup time for get is constant time, \$O(1)\$.

There is however, somethings that I can point out.

Final

Whenever possible, add the keyword final to member fields of your class. This keyword should be used for values/references that never change. Your namesToAnimation and animations variables can be marked with final.

Why Map<String, Integer>?

You seem to only use your namesToAnimation as a lookup for String to index in the 'animations' list. You never increase/decrease your currentAnimation value. Then why do you use Map<String, Integer>? I think you can get rid of your list entirely and use Map<String, Animation>

Rewritten code according to what I have mentioned above:

public class AnimationSet {

    private Animation currentAnimation;
    private final Map<String, Animation> animations;

    public AnimationSet() {
        animations = new HashMap<>();
    }
    public void addAnimation(String title, Animation animation){
        animations.put(title, animation);
    }
    public void goToAnimation(String title){
        currentAnimation = animations.get(title);
    }
    public void removeAnimation(String title){
        animations.remove(title);
    }
    public void draw(Graphics2D g, int x, int y){
        g.drawImage(currentAnimation.getImage(), x, y, null);
    }
    public void update(){
        currentAnimation.update();
    }
}

Usefulness

I'm sorry, but I can't really understand why you have this class? What functionality does it provide to you? Would it be easier to have the same functionality without this class?

Hopefully you have a good use case for this class, in which case, great! I'm just not sure how I myself would use this class, which brings me to the next point:

Documentation

Although your naming is really good (you have no idea how happy I am to be able to say that!), your class could use some documentation in the form of JavaDoc. Stating the purpose of the class and the usage of the class and it's methods in JavaDoc helps any potential users of your class, it can even help yourself several times.

Thread safety

Your code would likely cause problems if it would be used from multiple threads. To avoid those problems, learn about Java Concurrency. If you're not using multiple threads now, you might be later, that's why I'm mentioning this. It's something for you to learn in the future :)


Read through and bookmark the C++ Standard Guidelines.  Numbers I note later are citations from this.

Don’t write using namespace std;.

You can, however, in a CPP file (not H file) or inside a function put individual using std::string; etc.  (See SF.7.)

#define MAXN 500

Don't use #define for constants or "functions" (⧺ES.31).

void recurse( int task_idx, int cpus_used_so_far, int  exit_time_of_task_in_CPUs[] ){

That last parameter is a pointer, with the implication that you are passing a pointer to the first of contiguous elements.  Don’t pass unknown-sized arrays like that.

(Reading ahead…) since it is of fixed size known at compile time, define it as a std::array instead, both the actual array in main and the parameter (by reference).

int min_cpus_used = 6;

int exit_time_of_task_in_CPUs[5]={0};

if (cpus_used_so_far+1 <= 5){

if(min_cpus_used==6){

Hard-coded magic numbers: are these all related?  Define a constant instead of sprinkling these throughout the code.

Let’s see… cpus_used_so_far is not changed within the function, just passed a different value when recursing, right?  It would be helpful for readability and analysis to mark it const in the declaration.

    if (cpus_used_so_far+1 <= 5){
            ⋮
    }else{
        return ;
    }

That took me a moment to figure out what the else return was doing at the end of the function just before the closing braces.  This would be much clearer if you invert the logic:  put the exceptional case first, in the manner of precondition testing.

if (cpus_used_so_far+1 > 5)  return;
⋮

Note that there is no further indenting of the regular code, since it is not nested anymore — it is the main-line of code.

cin.tie(NULL);

Don’t use the C macro NULL.  For a null pointer, it is the keyword nullptr.

    cout<< -1 <<endl;

Don’t use endl.  Just use \n.


Calculating large powers of 2 in decimal

How I can make this algorithm better?

Here's how I would make your algorithm better.

First: your principle is sound. You are displaying a large binary number in base 10 by taking advantage of the fact that int already has a method that displays a 32 bit number in base 10.  Essentially your method is:

convert the number to base 10000, by making an int array "digits" from 0 to 9999.
Make a device which can double one of those numbers
Print the result after the given number of doublings.

This technique works, but your implementation could use some improvements. The improvements I would make are:

Go big!  Why base 10000?  You could do base 100000000 in an int no problem or base 1000000000000000000 in a long.  Let's do that.
You allocate a huge number of ints.  That's probably either way too many or way too few for the problem at hand.  Don't limit yourself. Make a solution that grows as you need it, not one that has an arbitrary limit.  Moreover: you make 3750 ints, but you could do the entire problem with only 167 longs.
Abstract away your operations into a type that represents the value
Refactor each part of the algorithm into a helper method that does one thing well.
Stop using mutable state. It's OK to burn a little memory. The garbage collector will deal.
Use a more efficient algorithm to calculate big powers.

How might we put these principles into practice? Let's try.

First off, I'm going to make a struct which represents a number encoded in base 1000000000000000000.  Its implementation will be a list of longs, but it could be any collection type. Lists are just convenient.

(Aside: Why a struct? The implementation is small; it's a wrapper around a single reference. The meaning of the struct is logically a value.  It is immutable.  So this is a good candidate for a value type.  We get the benefits of having a clean interface and implementation hiding, but we only pay the price of a single reference.)

struct Base1000000000000000000
{
    private List<long> digits;
    private Base1000000000000000000(List<long> digits) {
        this.digits = digits;
    }

Note that so far everything is private. I want this to have a very locked-down interface.  We've got to get this party started somewhere, so let's represent one:

  public static readonly Base1000000000000000000 One =
    new Base1000000000000000000(new List<long> { 1L });

You could do Zero similarly.

Now what does our display algorithm look like? That's a one-liner:

public override string ToString() =>
    string.Join("",
        ((IEnumerable<long>)digits)
          .Reverse()
          .Select(d => d.ToString().PadLeft(18, '0')));

Note that we're using the non-destructive reverse, not the destructive reverse on list.

The core of the algorithm is in our adder, which takes a number and returns its double:

  public Base1000000000000000000 DoubleIt()
  {
    // Note, _ separators in constants are new for C# 7.
    const long TheBase = 1_000_000_000_000_000_000;
    var result = new List<long>();
    result.Add(0);
    for (int i = 0; i < this.digits.Count; i += 1)
    {
      // Make sure we have storage.
      if (i == result.Count)
        result.Add(0);
      result[i] += this.digits[i] + this.digits[i];
      // We might have to carry.
      if (result[i] >= TheBase)
      {
        // Again, make sure we have room.
        if (i + 1 == result.Count)
          result.Add(0);
        result[i+1] = result[i] / TheBase;
        result[i] -= TheBase;
      }
    }
    // And we're done.
    return new Base1000000000000000000(result);
  }

Super.  Now the main algorithm is straightforward:

Base1000000000000000000 c = Base1000000000000000000.One;
for (int i = 0; i < n; ++i)
  c = c.DoubleIt();
return c.ToString();

Notice how when I extract each operation to its own method, the code becomes simpler and more elegant.

Now, how can you improve this further?

Exercise: (Easy) Implement operator+ on this type.
Exercise: (Pretty Easy) Implement operator- on this type, and represent negative numbers correctly.
Exercise: (Hard) Implement operator* on this type.
Exercise: (Very hard) Now that you have multiplication and addition, you can get to 2n much faster. Suppose you want to do 2384.  Start with One.  Double it.  Now you have 21.  Multiply it by itself -- square it.  Now you have 22.  Square it again to get 24. Square it again to get 28.  And so on, until you have them up to 2256.  Multiply 2256 by 2128 to get 2384, and you're done.  Your original algorithm does 384 doublings, but you can get the answer with one doubling and nine multiplies. Can you work out the algorithm for the optimal sequence of multiplications and additions?
Exercise (Very hard): Implement % and / on this type.
Exercise (Very very hard): Now do it all over again without using any built-in type for the math. (Obviously use string for the text.)  You are leveraging the ability of int or long to represent a bitfield that can be displayed in base 10.  What if you didn't have that?  Because someone had to write that code. The person who wrote that code didn't have it because it hadn't been written yet.  Suppose C# didn't have any integer type; how would you implement math from scratch?


CSS/JS slider using just data-attributes and transform:translate

My question is: do you maybe see any relevant drawbacks on this technique?

I don't see any drawbacks with the technique.

I do however see an improvement with the functions bound to the click handlers:

next_button.on('click', function(e){ goto('next'); });
prev_button.on('click', function(e){ goto('prev'); });

These can be simplified using partially applied functions:

next_button.on('click', goto.bind(null, 'next'));
prev_button.on('click', goto.bind(null, 'prev'));

And since the else condition doesn't really check the value of direction you could cheat and just use goto as the bound function on the previous button click hander:

prev_button.on('click', goto);

Additionally, while it may utilize a few more function calls (thus being slightly slower) the code within goto() could be simplified using Math.min() and Math.max():

if(direction == 'next'){
    current = Math.min(slides.length, current + 1);
} else {
    current = Math.max(current - 1, 0); // zero-based
}

var slide_strip = $('.slides');
var slides = slide_strip.find('> *');

var next_button = $('.next-button');
var prev_button = $('.prev-button');

next_button.on('click', goto.bind(null, 'next'));
prev_button.on('click',goto);

function goto(direction){
  var current = parseInt(slide_strip.attr('data-current'), 10);

  if(direction == 'next'){
    current = Math.min(slides.length, current + 1);
  } else {
    current = Math.max(current - 1, 0);
  }

  slide_strip.attr('data-current', current);
}
.main-box {
  max-width: 600px;
  margin: 0 auto;
}

.slide-box {
  overflow: hidden;
}

.slides {
  background-color: #656565;
  display: flex;
  flex-wrap: nowrap;
  transition: -webkit-transform 300ms;
  transition: transform 300ms;
  transition: transform 300ms, -webkit-transform 300ms;
}
.slides[data-current="1"] {
  -webkit-transform: translateX(0%);
          transform: translateX(0%);
}
.slides[data-current="2"] {
  -webkit-transform: translateX(-100%);
          transform: translateX(-100%);
}
.slides[data-current="3"] {
  -webkit-transform: translateX(-200%);
          transform: translateX(-200%);
}
.slides[data-current="4"] {
  -webkit-transform: translateX(-300%);
          transform: translateX(-300%);
}
.slides[data-current="5"] {
  -webkit-transform: translateX(-400%);
          transform: translateX(-400%);
}
.slides[data-current="6"] {
  -webkit-transform: translateX(-500%);
          transform: translateX(-500%);
}
.slides[data-current="7"] {
  -webkit-transform: translateX(-600%);
          transform: translateX(-600%);
}
.slides[data-current="8"] {
  -webkit-transform: translateX(-700%);
          transform: translateX(-700%);
}
.slides[data-current="9"] {
  -webkit-transform: translateX(-800%);
          transform: translateX(-800%);
}
.slides[data-current="10"] {
  -webkit-transform: translateX(-900%);
          transform: translateX(-900%);
}
.slides[data-current="11"] {
  -webkit-transform: translateX(-1000%);
          transform: translateX(-1000%);
}
.slides[data-current="12"] {
  -webkit-transform: translateX(-1100%);
          transform: translateX(-1100%);
}
.slides[data-current="13"] {
  -webkit-transform: translateX(-1200%);
          transform: translateX(-1200%);
}
.slides[data-current="14"] {
  -webkit-transform: translateX(-1300%);
          transform: translateX(-1300%);
}
.slides[data-current="15"] {
  -webkit-transform: translateX(-1400%);
          transform: translateX(-1400%);
}
.slides[data-current="16"] {
  -webkit-transform: translateX(-1500%);
          transform: translateX(-1500%);
}
.slides[data-current="17"] {
  -webkit-transform: translateX(-1600%);
          transform: translateX(-1600%);
}
.slides[data-current="18"] {
  -webkit-transform: translateX(-1700%);
          transform: translateX(-1700%);
}
.slides[data-current="19"] {
  -webkit-transform: translateX(-1800%);
          transform: translateX(-1800%);
}
.slides[data-current="20"] {
  -webkit-transform: translateX(-1900%);
          transform: translateX(-1900%);
}
.slides .slide {
  height: 300px;
  min-width: 100%;
  background-color: #ffb0b0;
}
.slides .slide:nth-child(even) {
  background-color: #ff8181;
}

1

2

3

4

5

6

7

        <button type="button" class="prev-button">prev</button>
        <button type="button" class="next-button">next</button>


Robots files generation - simplifying foreach code

If number of lines is your primary concern, then really all we can do with this is merge your array creation lines, and use array_merge() to create temporary arrays which you can loop around, like so:

public function generateRobotsFile($rbfile, $smfile)
{
    $tab = array('SemBot' => array('Googlebot', "bingbot\nCrawl-delay: 5", 'MSNBot'),
                 'Lang'   => array('eb'),
                 'Files'  => array('address.php', 'cart.php'),
                 'Folder' => array('classes', 'docs', 'themes'));
    fwrite($writeFd, "\nUser-agent: *\n");
    foreach(array_merge($tab['Lang'], $tab['Folder']) as $disallow)
    {
        fwrite($writeFd, 'Disallow: ' . __PS_BASE_URI__ . $disallow . "\n");
    }
    foreach($tab['SemBot'] as $SemBot)
    {
        fwrite($writeFd, "User-agent: " . $SemBot . "\n");
        foreach(array_merge($tab['Files'], $tab['Folder']) as $disallow)
        {
            fwrite($writeFd, 'Disallow: ' . __PS_BASE_URI__ . $disallow . "\n");
        }
    }
}


I saw your post on python-ideas. I think you have a misconception about native coroutines (i.e. async def). For example, this method in AsyncDict:

async def items(self):
    items = super().items()
    for item in items:
        yield item

This method does not have any await expressions, therefore the method itself should not be async def. It should just be a regular def. You may not realize it, but an async def function can still call regular def functions, and it can use regular with and for blocks.

In your use case, you should use a regular dictionary and a regular for loop:

calls = {"!ping": ping}

@client.event
async def on_message(message):
    for k, v in calls.items():
        if message.content.startswith(k):
            await v(message)

This is perfectly legal, and in fact better than trying to create "Async" variants of common data structures that don't need it.


Which will be better declaration go to with TypeScript?

Your question is a bit too abstract. Both ways are okay in different scenarios. You may even have a mixture of two patterns in the same code base... Sorry, but yes, my answer is "it depends".

I think, the key here is the intent and the way it's conveyed via code. If ActionSet's behavior is rigid, and "known in advance", you may want to declare it as a class (as in first example). This will make sure that even when an instance is created NOT by using createActionSet() it still obeys the same behavior rules.

If however, your entity is not rigid and you don't know all its possible usages in advance, it's probably better to start with an interface and a set of factory functions (as in second example).

Since the context of the question is not really known, I hesitate to go beyond this explanation and recommend a particular one.

In my practice interfaces have always been "handier", more refactorable, and easier to deal with. I do pick them as defaults today and rarely go to classes. This, however, is mostly true to DTO-alike classes ("dummy" classes with little to no behavior whatsoever). I find it helpful to separate the data transfer entities from the data processing entities, but it (again) could be due to the client-server-comm saturated nature of my applications.

Use your own judgement! :)


Convert Sorted Array to Height Balanced Binary Search Tree

A class Solution with only public members can be written struct Solution.  But with only a single member function (that never uses the this pointer), why not a free function?

Presumably your vector is intended to be a std::vector, in which case we need #include <vector> and the correct namespace qualifier.

Don't pass a reference to a mutable object unless it's reasonable for the function to modify it.  In this case, we just want to copy from it, so pass a const std::vector<int>& instead.

You're right that it's very inefficient to make many new containers, when we just want a view; that's exactly what iterator-pairs (aka ranges) are good for.  I'll not consider the first version any further.

There's no need to accept only vectors of int - we'd like to accept any ordered random-access container, of any element type.  That's easy enough, with a template:

template<typename RandomAccessIterator>
TreeNode* makeBST(RandomAccessIterator start, RandomAccessIterator end){

There's a serious bug when new TreeNode() fails: all the allocated nodes further up the call tree will be leaked as the std::bad_alloc propagates upwards.  It's better to make the BST use smart pointers.  If you can't change that implementation, then we can achieve exception safety by holding each root in a smart pointer until after the potentially-throwing recursive calls:

    auto root = std::make_unique<TreeNode>(*mid);
    root->left = makeBST(start, mid);
    root->right = makeBST(mid + 1, end);
    return root.release();


Interesting question,

I would go with this:

create: function (registerDetails, found, notfound) {

    db.User.findOne({
        username: registerDetails.username
    }).exec(queryCallback);

    function queryCallback(err, user) {
        if (user != null) {
            found(user);
        } else {
            var newUser = new db.User();
            newUser.username = registerDetails.username;
            newUser.password = registerDetails.password;
            newUser.save(saveCallback);
        }
    };

    function saveCallback(err, user) {
        notfound(user);
    };
},

Basically, I

Used the fact that JavaScript does hoisting, you can use functions prior to having them declared. Given this I put the .exec() on top, I also did away with query which I would have called userQuery.
I put proper braces and newlines around if( user!= null ), to be tested, but if you can get away with it, you should consider if(user)
I moved from var xx = function() to function xx() because anonymous functions in stacktraces are not fun


Adding ID to body tag from variable defined in URL

One technique is to default the value to NULL:

$var = NULL;
if (isset($_GET['var'])) {
    $var = $_GET['var'];
} ?>

Then when setting the attribute on the tag, isset() doesn't need to be used.

<body class="whatever" <?php if($var) {echo "id=\"$var\""; } ?>>

For a demonstration of this, see this phpFiddle.

Note that it is recommended that PHP not be mixed in with HTML code. For a good explanation, refer to this answer to Should I Include PHP code in HTML or HTML in PHP? on the Software Engineering site.

  Mixing languages is not a good idea. You don't put JavaScript in HTML, or HTML in JavaScript, or JavaScript in PHP, or HTML in Python or Ruby in SQL.1

As is recommended by that post, consider the use of templates:

  What are you probably looking for is called templates. Depending on the framework you use, it may already be available, usually under a form of MVC, where the template is in the view, or you may have to use a third-party template engine, such as Smarty.

  In both cases, the idea remains the same. You have PHP code strictly separated from the template which contains the HTML and a bit of very simplistic logic: simple loops over entities, conditions for conditional displaying of information, etc. When the PHP code is ready, it calls the template engine, passing to it some information. The engine uses a specific template to build the final output (often HTML, but other formats are possible as well) which is then sent to the user.1

1https://softwareengineering.stackexchange.com/a/291839/244085


Count the numbers without consecutive repeated digits

The problem statement gives a great hint: mathematics. So do not brute force.

Fix the leading digit less than the leading digit of \$N\$ (including zero). For the next digit you have 9 choices (to avoid repetition). For the next digit you again have 9  choices, etc. The is, any leading digit less than the leading digit of \$N\$ gives \$9^k\$ "good" numbers.

With a leading digit equals to leading digit of \$N\$ you have less choices, because you have to stay below \$N\$. The best way to deal with is is to remove the leading digit of \$N\$, and apply the same logic to the remaining number.

For example, for \$N=3456\$ it works like this \$3 \times 9^3 + 4 \times 9^2 + 5 \times 9 + 6 = 2562\$

Now convert it to the code.

Hint: you can also go right to left.


You can further improve this by making it a jQuery plugin instead to make it reusable across any element.

non-IE browsers, combined, account for ~60% of users at the time of writing. This means 60% of the time, the two conditions are evaluated since you check for IE first. Instead, reverse the conditions to get it right on the first check 60% of the time.

$.fn.OneClickSelect = function () {
  return $(this).on('click', function () {

    // In here, "this" is the element

    var range, selection;

    if (window.getSelection) {
      selection = window.getSelection();
      range = document.createRange();
      range.selectNodeContents(this);
      selection.removeAllRanges();
      selection.addRange(range);
    } else if (document.body.createTextRange) {
      range = document.body.createTextRange();
      range.moveToElementText(this);
      range.select();
    }
  });
};

// Apply to these elements
$('p, #all-select').OneClickSelect();


This seems to me like your create_threads and run_cracker functions are trying to reinvent something that look like multiprocessing.Pools. Using them, you just need to implement crack_password, managing the workload and spawning processes will be done by the pool.

This will however not short-circuit once a working password has been found.

Example implementation:

from multiprocessing import Pool

import requests

def crack_password(password, url='http://localhost/login.php'):
    response = requests.post(
        url,
        data={'username': 'admin', 'Login': 'Login', 'password': password}
    )

    if bytes('Login failed', encoding='utf-8') not in response.content:
        return password

def main(passwords_filename='common-passwords.txt'):
    with open(passwords_filename) as passwords_file:
        passwords = passwords_file.readlines()

    with Pool(4) as pool:
        results = pool.map(crack_password, passwords)
        success = list(filter(None, results))
    print(success)

if __name__ == '__main__':
    main()


Validating a string under few conditions

As I think George Howarth was suggesting in his answer you can reduce nesting and avoid the Arrow code effect by returning early from the
method.  This helps with code flow as well as readability.
As already mentioned if you can remove constant literals from your code that is good. One way to do this is to move these to
private static or const variables or even supply them to the method.

private const int RequiredLength = 10;
private readonly char[] _acceptedLastCharacters = { 'x','v' };

I like to try and remove dependecies from the view especially in business logic which validation can often be.  So in this case
I would consider returning a result class and let your caller determine how to handle it.  This would also mean creating unit tests
would be so much easier which I think in this case would be ideal.

internal class ValidationResult
{
  public bool IsValid { get { return string.IsNullOrEmpty(ErrorMessage); } }
  public string ErrorMessage { get; private set; }

  private ValidationResult(string errorMessage)
  {
      ErrorMessage = errorMessage;
  }

  public static ValidationResult Success()
  {
      return new ValidationResult(string.Empty);
  }

  public static ValidationResult Failure(string errorMessage)
  {
      return new ValidationResult(errorMessage);
  }

}
A great thing about writing unit tests is that it can sometimes ensure you think about your requirements before you even code and so
help cover everything.  In this case I was writing some unit tests for the method and it occured to me that the code might not cover the case
of empty strings.  I created the test and hello, it had worked.  That was great.  Now I also have a test!  And not only that, doing a couple
of other tests showed some flaws in my code which meant I identified problems with tests.  Awesome!

Here is an example of the entire re-factored code:

internal class ValidationResult
{
    public bool IsValid { get { return string.IsNullOrEmpty(ErrorMessage); } }
    public string ErrorMessage { get; private set; }

    private ValidationResult(string errorMessage)
    {
        ErrorMessage = errorMessage;
    }

    public static ValidationResult Success()
    {
        return new ValidationResult(string.Empty);
    }

    public static ValidationResult Failure(string errorMessage)
    {
        return new ValidationResult(errorMessage);
    }
}

class NicValidator
{
    private const int RequiredLength = 10;
    private readonly char[] _acceptedLastCharacters = { 'x','v' };

    public ValidationResult ValidateNic(string nic)
    {
        var trimmedNic = nic.Trim();

        if (trimmedNic.Length != RequiredLength)
        {
            return Failed("NIC cannot be empty and is not of required length " + RequiredLength);
        }

        if (!_acceptedLastCharacters.Contains(trimmedNic.Last()))
        {
            return Failed(string.Format("Last letter is not supported and should be one of [{0}]", string.Join(",", _acceptedLastCharacters)));
        }

        // Ignore last character as that is handled in earlier check
        var illegalCharacters = trimmedNic
            .Take(trimmedNic.Length - 1)
            .Where(p => !char.IsNumber(p))
            .ToList();

        if (illegalCharacters.Any())
        {
            string errorMessage = string.Format("letters {0} are not allowed, all Should be numbers except the last one.",
                string.Join(",", illegalCharacters));

            return Failed(errorMessage);
        }

        return ValidationResult.Success();
    }

    private ValidationResult Failed(string errorMessage)
    {
        return ValidationResult.Failure(errorMessage);
    }
}

With some unit tests (I didn't do all, just enough to test base functionality).  Note.  I started these tests before I
even started re-factoring the code so that I had them passing first.  Then during re-factoring I could confidently know
whether what I did was still returning the correct results.

[TestMethod]
public void StringIsOfRequiredLength()
{
    // arrange
    var validator = new NicValidator();
    const string nic = "123456789x";

    // assert
    var result = validator.ValidateNic(nic);

    // act
    Assert.IsTrue(result.IsValid, result.ErrorMessage);
}

[TestMethod]
public void StringIsNotOfRequiredLength()
{
    // arrange
    var validator = new NicValidator();
    const string nic = "12345678x";

    // assert
    var result = validator.ValidateNic(nic);

    // act
    Assert.IsFalse(result.IsValid, result.ErrorMessage);
}

[TestMethod]
public void NicIsNotAllSpaces()
{
    // arrange
    var validator = new NicValidator();
    const string nic = "          ";

    // assert
    var result = validator.ValidateNic(nic);

    // act
    Assert.IsFalse(result.IsValid, result.ErrorMessage);
}


There are many encoding formats that could lead to this string. One of them is JSON. So instead of writing the splitting code yourself, you should use one of the many existing JSON parsers. Have a look at the awesome-java project at GitHub to find one.

Then, your code should become as simple as:

JSONArray sampleList = JSON.parseArray(sample);


Sum of all numbers whose remainder and quotient are the same

Since this is Code Review, here's a clean-up of your code:

from itertools import count

def sum_numbers_with_equal_quot_rem(divisor):
    result = 0

    for num in count(1):
        if num % divisor == num // divisor:
            result += num

        if num // divisor > divisor:
            break

    return result

sum_numbers_with_equal_quot_rem(40)
#>>> 31980

sys.maxint is the largest int, but not the largest integer, so your loop was broken (although it would have taken a while to find out). This fixes that and makes it Python 3 compatible.

Now, let's add some introspection:

if num % divisor == num // divisor:
    result += num
    print(num % divisor, num // divisor)

and for divisor = 40 we get

1 1
2 2
3 3
4 4
5 5
...
37 37
38 38
39 39

This makes sense as num is fully determined by its divisor and remainder and there must be at least one number with divisor = remainder = k for k in range(1, divisor). There isn't one for 0 or less and there isn't one for divisor or more. This suggest we use:

def sum_numbers_with_equal_quot_rem(divisor):
    result = 0

    for quot_rem in range(1, divisor):
        num = quot_rem * divisor + quot_rem
        result += num

    return result

where num = quot_rem * divisor + quot_rem comes from

help(divmod)
#>>> Help on built-in function divmod in module builtins:
#>>>
#>>> divmod(...)
#>>>     divmod(x, y) -> (div, mod)
#>>>
#>>>     Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
#>>>

Namely, the invariant div * y + mod == x.

This gives us an even better option, if we look carefully.

Compare these:

k * divisor + k
(k+1) * divisor + (k+1)

They differ by 1 * divisor + 1. So we are adding up:

$$
1 \, (\text{divisor} + 1) + 2 \, (\text{divisor} + 1) + \cdots + (\text{divisor} - 1)(\text{divisor} + 1)
$$

Letting \$\text{divisor} = d\$, this is just

$$
(d + 1) \sum_{k=1}^{d - 1} k = (d + 1) \left( \frac{1}{2} (d-1) \, d \right) = \frac{d^3 - d}{2}
$$

giving the much simpler

def sum_numbers_with_equal_quot_rem(divisor):
    return (divisor**3 - divisor) // 2

sum_numbers_with_equal_quot_rem(40)
#>>> 31980


Many nested session verification conditions

This is indeed quite messy. It's really hard to see which else ends which if.

Just invert the if and return early:

if( !isset($_SESSION["access_token"], $_SESSION["user_email"], $_SESSION["username"]) ){
    return false; // mean doesn't have account. Register user and send verification to email
}

if(!$GoogleAccess->does_account_exist){
    return "This account has been banned";
}

if($GoogleAccess->is_g_acc_banned()){
    return "Your IP's been banned";
}

...

Alternatively, if you don't have a function, you could also phrase it with if-elses:

if( !isset($_SESSION["access_token"], $_SESSION["user_email"], $_SESSION["username"]) ){
    return false; // mean doesn't have account. Register user and send verification to email
} else if(!$GoogleAccess->does_account_exist){
    $error = "This account has been banned";
} else if ($GoogleAccess->is_g_acc_banned()) {
    $error = "Your IP's been banned";
}

...

Personally, I prefer the first approach, as it's a lot more readable.

I'm not familiar with google access, but it seems odd that you have to manually check all the access denied reasons. I would expect that you call their API, and it either logs a user in, or returns the reason why that was not possible. Did you check if something like this exists? It would severely simplify your code.


I've done my best to get you pointed in the right direction, but your code is difficult to follow as is. Here is what I have:

Sub Test()
    Dim wsheet1 As Worksheet
    Set wsheet1 = ActiveWorkbook.Worksheets("Sheet1")

    Dim wsheet2 As Worksheet
    Set wsheet2 = ActiveWorkbook.Worksheets("Sheet2")

    ' Use the Range object, and not the 'Object' object
    Dim data1Range As Range
    Set data1Range = wsheet2.Range(wsheet2.Range("C1"), wsheet2.Cells(Rows.Count, 1).End(xlUp))

    ' I prefer clearer variable names
    Dim InputData As Variant

    ' I am making the somewhat dangerous assumption here that the only data on this sheet is the data you need in the array.
    InputData = wsheet2.UsedRange.value

    ' I am creating this boolean because I am a little too lazy to do a fancier function approach.
    ' This is purely to get a satisfied condition from the Select Case statement, and as a result to skip the corresponding conditional block.
    Dim SatisfiesConditions As Boolean

    ' I dont know what kind of value you're retrieving from the corresponding cells, so I am using variants as a temporary type.
    Dim MatchedValue As Variant
    Dim OffsetValue As Variant

    Dim SearchNum As Range
    Dim FirstAddress As String
    Dim x As Long

    ' I assume here that your data has headers, so I loop from the lowest bound (first row) plus 1 (offset for header row) to the maximum row
    For i = LBound(InputData, 1) + 1 To UBound(data1, 1)
        ' To use an array, reference the array index and not the worksheet index
        ' Additionally, use 'Select Case' for multiple 'Or' conditions.

        SatisfiesCondition = True

        Select Case InputData(i, 3)
            Case "Mike"
            Case "Sam"
            Case "George"
            Case "Abrahim"
            Case Else
                SatisfiesCondition = False
        End Select

        If SatisfiesCondition Then
            MatchedValue = InputData(i, 3)

            ' Since the offset was 7, 3 + 7 = 10
            OffsetValue = InputData(i, 10)

            ' From here down, it is difficult to understand what you are doing. xOffset isn't declared (or assigned)
            If InStr(1, xoffset, "1.") <> 0 Then
                With wsheet2.Range("a1:a" & lastrow)
                    Set SearchNum = .Find(wsheet2.Range("J" & i).value, LookIn:=xlValues)

                    If Not SearchNum Is Nothing Then
                        FirstAddress = SearchNum.Address

                        ' This loop should be infinite since searchNum will always be assigned to the same exact
                        ' address, and as a result the condition will always be satisfied.
                        Do
                            SearchNum.Offset(columnoffset:=3).Copy
                            wsheet1.Range("B" & x).PasteSpecial
                        Loop While Not SearchNum Is Nothing And SearchNum.Address <> FirstAddress
                        x = x + 1
                    End If
                End With
            End If
        End If
    Next
End Sub

I noticed a few points where you code looks as though it shouldnt actually work. You also had a mix of variables declared and never used, and variables used but never declared.

The Big Stuff

First, multiple Dim statements are always preferable to a single Dim statement for multiple variables

Dim Foo as Long
Dim Bar as String
Dim Baz as Worksheet

Is better than

Dim Foo as Long, Bar as String, Baz as Worksheet

It is also best to declare variables as close to first use as possible (outside of loops though). You'll notice that I implemented this in my refactoring of your code.

Option Explicit

I highly encourage the use of Option Explicit within your code. This will give you a compile-time error any time you try to compile your code when a variable is used but undeclared. This helps with things like:

Dim Fooo as String
Fooo = "SomeString"

...many lines later...

If Foo = "SomeString" Then
    ' Never is satisfied since Foo is not the same as Fooo
End If

To make Option Explicit easy, do this:
    Alt + T
    Alt + O
    Editor Tab
    Make sure 'Require Variable Declaration' is checked

Indentation

Make sure your code is properly indented before posting it. If you did, you would've noticed that you were missing the Next at the end of your For block (which prevents the code from compiling). You would've also noticed the lack of Sub and End Sub.

Select Case vs. If...Or...Or...Or...Or...

Any time you are doing multiple "If it is this, or that, or..." conditionals, you should use a Select Case statement. There is a slight performance increase, but it is also cleaner and easier to read.

Additionally, it makes it easy to edit the conditions as needed.

Select Case works by taking an input variable, and checking the condition against Case's. If the condition matches, it runs the code inside the Case block, otherwise it goes to Case Else or End Select in the absence of Case Else.

For example:

Dim Foo as String
Foo = "Apple"

Select Case Foo
Case "Apple"
    msgbox "Foo is an Apple!"
Case "Pear"
    msgbox 'Foo is a Pear!'
Case "Orange"
    msgbox "Foo is an Orange!"
Case Else
    msgbox "Foo is an " & Foo & "!"
End Select

' Outputs a messagebox that says "Foo is an Apple!"

Dim Foo as String
Foo = "Banana"

Select Case Foo
Case "Apple"
    msgbox "Foo is an Apple!"
Case "Pear"
    msgbox 'Foo is a Pear!'
Case "Orange"
    msgbox "Foo is an Orange!"
Case Else
    msgbox "Foo is an " & Foo & "!"
End Select

' Outputs a messagebox that says "Foo is a Banana!"

The beauty of Select Case is that you can have code within the Case Blocks or you can leave them empty and only have code in the Case Else block.

Arrays

This is the meat of what you are looking for. From your code, it looks like you misunderstood how to use arrays. Basically, arrays improve performance when the computations are done in the array (this is because they are being done in-memory versus in-worksheet).

When using an array for your purposes I would suggest setting the array equal to the entire range with your data in it. So for example, if you have a table on worksheet Sheet in `Range("A1:Z100") your array would be:

Dim SomeArray as Variant
SomeArray = ThisWorkbook.Worksheets("Sheet1").Range("A1:Z100").Value

This will return a 1-Based array that you can then loop through. Now, for example, if Column "C" should equal "B" * "A" you can do this:

Dim i as Long
For i = LBound(SomeArray, 1) + 1 to Ubound(SomeArray, 1)
    If IsNumeric(SomeArray(i, 1)) and IsNumeric(SomeArray(i, 2)) Then
        SomeArray(i, 3) = SomeArray(i, 2) * SomeArray(i, 3)
    End If
Next

Then we can quickly output it to the worksheet when we are done:

ThisWorkbook.Sheets("Sheet1").Range("A1:Z100").Value = SomeArray

Voila! We now have completed our computations much faster than if we had done the same thing on the worksheet.

I would recommend practicing with arrays and spending some time understanding what they do, how they work, and how to loop through them. They are very powerful when used well.

Rubberduck

If you haven't heard of it before, there is a tool called "RubberDuck" that can help tremendously with refining your code. It has inspections that can catch a lot of the common mistakes. It also improves the Project Explorer window immensely. Check it out here: http://rubberduckvba.com/

Locals, Immediate, and Watch Windows

If you aren't using these windows already you definitely should be. They make debugging much easier, and it also improves your ability to step through your code. You can find them in the 'View' menu of the IDE.

Best of luck!


Rendition of Project Euler 26 - reciprocal cycles

You don't have to define your own gcd function: it already exists in the fractions module of the standard library. And actually, it works with any integer type. Therefore, you can rewrite lcm as:

def lcm(numbers):
    """finds lcm of list of #s"""
    from fractions import gcd
    return reduce(lambda a,b: (a*b)/gcd(a, b), numbers)

Also, you shouldn't write == True in a conditional, a code like

if eggs == True:
    # do something

should be replaced by:

if eggs:
    # do something

I realized that youare actually using Python 2 (for some reason, I thought that you were using Python 3). Therefore, You can probably improve the function isPrime. You are currently using range in the function. range creates and returns a list. You should use xrange instead: xrange is a generator; it will generate and yield a new int at each iteration. Since you occasionally return early from your loop, you don"t always need to compute the whole list of integers, and xrange should be a best fit for this job.

def isPrime(k):
    for x in xrange(2, int(math.ceil(math.sqrt(k)))):
        if k % x == 0:
        return False
    return True


Option 1: Don't use a directive.
What you are trying to do does not actually require a directive. It is simple enough to play with the scope.

  $scope.expandAdd = function() {
    $scope.hiddenAdd = true;
  };

  $scope.addWeb = function() {
    $scope.hiddenAdd = false;
  };

plnkr


Program for CodeHS 8.3.8: Word Ladder in Python 3

While your code seems to work, the next step should be separating the different responsibilities of your code. As far as I can see, there are three:

You have to ask the user for an index. It needs to be an integer in the range [-1, len(s)).
You have to ask them for a replacement character. It must be exactly one lower case character.
You need to actually run the game.

The first two can be combined into a general function asking the user for input with type and validation:

def ask_user(message, type_=str, valid=lambda: True, invalid="Invalid"):
    while True:
        try:
            user_input = type_(input(message))
        except ValueError:
            print(invalid)
            continue
        if not valid(user_input):
            print(invalid)
            continue
        return user_input

And your main program can then use this function. I would also change the internal data of the word to be a list, so you can easily replace characters. When printing the word, just use "".join(word).

def play_word_ladder():
    word = list(input("Enter a word: "))

    def valid_index(i):
        return i in range(-1, len(word))

    def valid_character(c):
        return len(c) == 1 and c.islower()

    while True:
        index = ask_user("Enter an index (-1 to quit): ",
                         int, valid_index, "Invalid index!")
        if index == -1:
            return
        char = ask_user("Enter a letter: ", str, valid_character,
                        "Character must be one lowercase letter!")
        word[index] = char
        print("".join(word))

Note that your outer for loop is completely unnecessary.

The game can be started under a if __name__ == "__main__": guard to allow importing from this script. Note that you don't need to manually exit the script, it will do so automatically at the end.

if __name__ == "__main__":
    play_word_ladder()


I think that is easier to write and understand the state change if you don't need to think about the edge cases.
In the first case, you already start in the state that you want and only need to invert the both states. In the second, you just need to "turn off" every states and "turn on" the one that you want to.
I think that is simplier if you think this way.
Two sidebars
I think that you can use DOMTokenList.toggle():

const sidebars = document.querySelectorAll('.sidebar');
const icon = document.getElementById('icon');

const toggle = el => el.classList.toggle('hidden');

icon.addEventListener('click',() => sidebars.forEach(toggle));
/* the display value of a div is block by default */
.hidden {
  display: none;
}

first

second

icon

Docs:

DOMTokenList
Element.classList
DOMTokenList.forEach()

More than two sidebars
Maybe toggle can't be useful in this case. However, I think that datasets might help

const sidebars = document.querySelectorAll('.sidebar');
const btns = document.querySelectorAll('.btn');

const getSidebar = btn => btn.dataset.sidebar;

const hide = el => el.classList.add('hidden');

btns.forEach(btn =>
  btn.addEventListener('click', () => {
    const target = document.getElementById(getSidebar(btn));
    sidebars.forEach(hide);
    target.classList.remove('hidden');
  })
);
.hidden {
  display: none;
}

sidebar 1

sidebar 2

sidebar 3

<button class="btn" data-sidebar="first">1</button>
<button class="btn" data-sidebar="second">2</button>
<button class="btn" data-sidebar="third">3</button>


Dividing a long (arbitrary-precision) number by an integer

Bug
Given the input 91 and dividing by 9, your program gives 1 as the answer instead of 10.  The problem is here:
        int localQuotient = localDivident / divisor;
        if (localQuotient > 0) {
            quotient[j++] = toCharacter(localQuotient);
            localDivident -= localQuotient * divisor;
        }

You have an if statement that excludes localQuotient == 0, but it shouldn't.  This is what prevents the 0 from being output.
Code simplification
You also have two other special cases dealing with zeros that can be removed, because they are properly handled by the normal case code.  Your main loop should be reduced from 16 lines to these 6 lines:
for (i = 0, j = 0; i < length; i++) {
    localDivident = localDivident * 10 + toNumber(a[i]);
    int localQuotient = localDivident / divisor;
    quotient[j++] = toCharacter(localQuotient);
    localDivident -= localQuotient * divisor;
}


Function that takes a positive integer number and returns the next bigger number formed by the same digits

The question of finding the next permutation in lexicographic order is a classical one (going back 7 centuries) and well documented in the literature. E.g. Wikipedia gives the following algorithm:

  Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
  Find the largest index l greater than k such that a[k] < a[l].
  Swap the value of a[k] with that of a[l].
  Reverse the sequence from a[k + 1] up to and including the final element a[n].


Restructuring multiple variables into an array

I don't quite understand why you are using individual variables for the various items since all you are doing is outputting them as a group. It would be much cleaner to collect them into a collection. Perhaps something like this:

//Images
List images = [
  properties["headerImage"],
  properties["sidebarImage"],
  properties["footerImage"]
]

//Videos
List videos = [
  properties["mainVideo"],
  properties["sidebarVideo"],
  properties["overviewImage"]
]

With the output looking like this:

$(document).ready(function () {
    $('.mediaGallery').mediaFilters({
        images: '${images.join(",")}',
        videos: '${videos.join(",")}',
    });
});

That improves readability, and with the example you have given doesn't impact functionality.


Is this the way to use HibernateCompositeUser type for handling localized contents?

I'm not too familiar with Hibernate, so just some generic notes:

DBMSs usually have case-insensitive attribute names, so a lot of people use underscore to separate words in attribute and table names.

<column name="SHORTDESCRIPTION"/>
<column name="LONGDESCRIPTION"/>

In the case above SHORT_DESCRIPTION and LONG_DESCRIPTION would be easier to read.

Is SQL syntax case sensitive?

    Master_i18n master_i18n=Master_i18n.getInstance();
    master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), "nl_NL");;

Master_i18n.getInstance() call seems unnecessary, since on the next line the local variable is overwritten. The following is the same (and the first line might not be required at all):

Master_i18n.getInstance();
Master_i18n master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), "nl_NL");;

<id name="uuid" type="java.lang.String">

java.lang.String could be simply string here.

public Object nullSafeGet(ResultSet rs, String[] arg1,
        SessionImplementor arg2, Object arg3) throws HibernateException,
        SQLException {

    Master_i18n master_i18n=Master_i18n.getInstance();
    master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), "nl_NL");;

    //return Master_i18n.getName();
    return Master_i18n;
}

I think currently it does not compile, since return Master_i18n is uppercased Master_i18n which seems a class, not a local variable.

master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), "nl_NL");;

nl_NL could be a parameter/constant. (Does every caller want to use this locale?) (One of the semicolons is unnecessary at the end of the line.)
I'd use longer and more descriptive variable names than ps, rs, arg1, arg3. Longer names would make the code more readable since readers don't have to decode the abbreviations every time when they read the code and don't have to guess which abbreviation the author uses.

(Clean Code by Robert C. Martin, Avoid Mental Mapping, p25)
Master_i18n is rather an ugly class name. It does not follow the usual CamelCase naming convention.
It also looks like a singleton which is rather an antipattern nowadays. They make testing harder and often hide dependencies which leads to spaghetti code which is really hard to work with.

What is so bad about singletons?
TotT: Using Dependency Injection to Avoid Singletons
Eliminating static helper classes
The Singleton Pattern


Integration of data using Simpson's rule

#! /usr/bin/env python
import glob
import os
import fileinput
print "<SimpInt.py> a script to quickly calculate the area for a set"
print "of analytes. Written by Bas Jansen, Leiden University Medical"
print "Center, March 20th 2013."
print ""

# Simpson's rule
def integrate(y_vals,h):

The recommendation for python is four spaces for indentation, you appear to be using 2

  i=1
  total=y_vals[0]+y_vals[-1]

It's also recommended to have spaces around binary operators

  for y in y_vals[1:-1]:

Use for i, y in enumerate(y_vals, 1): rather then counting your own i value

    if i%2 == 0:
      total+=2*y
    else:
      total+=4*y
    i+=1
  return total*(h/3.0)

# Reads the reference file
ref=[]

I'd recommended not using an abbreviation her

for refs in glob.glob("*.ref"):
  fr=open(refs)

It's recommended to use a with block:

  with open(refs) as fr:
      do stuff with file
  file will be automatically closed here

That ensures your file will be closed even if an exception occours

  for line in fr.readlines():
    parts=line.rstrip('\n').split('\t')
    ref.append(parts)

You shouldn't really store the header ref here.

  fr.close()

# Initialize the output file
f=open('output.xls','w')
for i in range(1,len(ref)):
  f.write(ref[i][0]+"\n")
f.close()

# Find XY files in current directory
xy_files=[]
for files in glob.glob("*.xy"):
  xy_files.append(files)
  x=[]
  area=[]
  print "Parsing: "+files
  fh=open(files)
  for line in fh.readlines():

Actually this is the same as for line in fh:

    y=[float(i) for i in line.split()]
    x.append(y)
  fh.close()

  # Pick the XY window
  print "Progress indicator:"
  print "0%"
  for i in range(1,len(ref)):

Whenever possible, don't iterate over indexes. Instead iterate over the lists. So something like for line in ref[1:]: If you really need the indexes us enumerate

    obs=[]
    vals=0
    low=float(ref[i][1])-float(ref[i][3])
    high=float(ref[i][1])+float(ref[i][3])
    # Progress indicator
    if i %(len(ref)/10) == 0:
      print str(i/(len(ref)/10))+"0%"

Why divide by 10 just to add the 0 back?

    for j in range(0,len(x)):

Use for j in x: and then avoid the indexing

      if x[j][0] > low and x[j][0] < high:
        coords=[float(l) for l in x[j]]
        obs.append(coords)
        vals+=1

What's this for?

    if obs:
      y_vals=[]
      h=(obs[len(obs)-1][0]-obs[0][0])/len(obs)
      for k in range(0,len(obs)):
        y_vals.append(obs[k][1])
      area.append(integrate(y_vals,h))

  # Neat trick to append the area from other input files
  l = 0
  for line in fileinput.input('output.xls',inplace=1):

If you need to iterate over multiple sources at once, use a zip.

    print "%s\t%s\n" % (line.rstrip(),area[l]),
    l+=1

Your neat trick is what's killing you. This is designed for processing the output of some other program. Its not good for continually adding to the end of lines you have already written. What you should do is store everything in a big list and then output it at the end.

# Display the legend (& filenames) at bottom of output file
f=open('output.xls','a')
legend = "Peak"
for m in range(0,len(xy_files)):
  legend+="\t"+str(xy_files[m])
legend+="\n"
f.write(legend)
f.close()

# Being polite
raw_input("Finished, press any key to exit")


Adding automated integration tests is a great way to take testing to the next level, and what you've written is really good for a first attempt. Here are some pointers/suggestions that might help you along your way.

It's almost inevitable that your tests will end up effectively testing the same thing multiple times. As you've identified, most of your tests use the GetById method, and in fact all of them Insert a payment. The only potential problem this causes is that if one of those methods stops working you suddenly have most/all of your tests failing and it may not be immediately obvious where the problem is. In the grand scheme of things, this isn't that much of an issue as you'll almost certainly be able to figure out where the problem is by looking at the test output and/or by stepping through the test with a debugger.

Although it seems like your tests are very similar, a lot of the similarities are down to them sharing common setup steps, e.g. inserting a payment so you have something to get/update/delete. It is absolutely fine to have this sort of duplication in unit/integration tests, and again is inevitable in most circumstances. As the number of tests grows, you might find that it makes sense to pull out some of the setup into a separate method that's used by multiple tests. This is also fine to do, as long as it doesn't affect the readability of the test, so avoid using generic method names like Setup() and instead prefer clear (if slightly verbose) names like CreateRepositoryWithSinglePayment(testPayment).

The fluent payment builder makes it hard to know which properties are required and which are optional (if any). I can't advise a great deal on this without seeing the Payment or PaymentBuilder classes, but if all of the properties are required, consider just creating a Payment constructor that assigns parameter values to readonly properties. Then there's no doubt about what values are required to create a valid Payment.

One thing to be aware of when integration testing is that it's often easy to end up with shared state between tests. Here, you are inserting a payment into your database as part of every test and this is not always deleted afterwards (or at least there's no tear-down code included in your post). Since you are actually persisting something in a database, it will therefore exist across tests unless explicitly deleted after each test is run. This could result in some very confusing test behaviour in the future as your tests might not be testing what you intended! You should add a tear-down step by implementing IDisposable and deleting every payment in your test database inside the Dispose() method. This ensures that every test will start from the same fresh state.
On a similar note, be aware that you can get strange behaviour when running integration tests in parallel if they share the same data store(s). You're fine at the moment because by default xUnit runs test cases within the same class in serial, but if you had another test class using the same database these would be run in parallel by default. There are ways to control this behaviour,  but it's more something to be aware of as this shouldn't be an issue given your current test organisation.

You shouldn't need to provide the entire Payment object to delete it from the database. If you can read a payment by its Id using the GetById method then you should also be able to delete a payment by its Id. This should simplify the Delete test case somewhat.

There are plenty of other things you could test here. You've got tests for the 'happy' paths, i.e. the paths where everything goes as expected, but there are certainly lots of edge cases (or unexpected cases) that you could also test. Maybe you've already considered some/all of these, but off the top of my head:

What happens when you insert a payment that already exists in the database?
What happens when you try to read a payment that does not exist in the database?
What happens when trying to update a payment that doesn't exist in the database?
Can you update the payment with a null description? What happens if the description is really long or contains special characters? You'd probably want to use a [Theory] with [InlineData] to enumerate several different test cases if doing this.
What happens when updating properties other than the description?
What happens when trying to delete a payment that doesn't exist in the database?


The code isn't especially bad and it seems to cover all bases but I agree it's not nice to look at. Perhaps some architectural observations may assist you in making it cleaner.

Firstly, I would not recommend using - 1 as a special value to indicate that a property is set or not. In this particular context it places an additional burden on you as the developer to remember what it means. Simply rely on the fact that a property is defined or it isn't.

A second observation is that I shouldn't worry about type checking unless you permit different "kinds" of range objects. If you've published your API that states a range object should be passed to this function, then have confidence that it will be used that way. If you must have it, consider inverting it so you don't have to nest the chain of if statements inside it.

A pattern I have seen regularly in this kind of code is to merge the user object with a default one, and then ask the question "does this make sense? ". With that said, be careful with modifying what has been passed to the function, unless behaviour is clearly published somewhere. What can happen is the user of this function will create a dodgy range object that gets corrected by your function and used in the DB query. The key part of this story is the user didn't know what they did was wrong and will carry on regardless. If it's wrong, give an error or let the query take ages and timeout, they'll have to learn some time!


Here is a list of things I would improve:

variable naming - PEP8 recommends to use lower_case_with_underscores style of variable names
instead of a regular expression, you can use urlparse to parse the domain name
you can use a dictionary comprehension to construct a dictionary of sites
you don't actually need a boolean flag for your while loop - instead initialize an endless loop and break it once the input is valid
instead of calling .keys() and passing the "viewkeys" result to str.join() - you can pass your dictionary directly

Improved code:

from urllib.parse import urlparse

with open('sites.txt') as input_file:
    sites = {
        urlparse(url).netloc.split('.')[0]: url
        for url in input_file
    }

print('Sites: ', ', '.join(sites), '\n')

while True:
    search_site = input("Which site would you like to search?\n")
    if search_site in sites:
        url_search = sites[search_site]+'/search?q='
        print(url_search)
        break

Further thoughts:

make the code more modular and extract parts of the code into separate functions - at this moment, it is clear that you have 2 separate high-level things you do in the code - getting the dictionary of sites and getting the user's input
put the execution code to under the if __name__ == '__main__': to avoid the code to be executed on import
you don't actually need to handle the list of sites manually - StackExchange provides an API endpoint with that information


Function that adds two items from a list in search of those that will match some given sum

def main():
    k = 21
    listA=[10,11,3,7]
    print (k,' = '," + ".join([str(i and e) for i in listA for e in listA if k==(i+e)]))

main()

This minor change to your code will do what you're after.  Put a " + ".join( ) around your list creator and cast the (i and e) items to str, that will then join all string elements in the list together into a string with + as the separator (there are spaces in there, yes, and this is necessary to get the output you're after).

Proof of Concept (via tio.run) that shows you how this will execute.

Note I also made a change to add spaces around the equals sign, indentation, and extra spacing for readability, as well as indentation standardization (4 spaces for a single indentation level).


Using temporary variables or calling a method directly

Regarding speed and memory, both are completely equivalent.

The only thing this boils down to is readability. In which case the first option has an advantage.

By storing the Button button = (Button) findViewById(R.id.button_english_splash); in a temporary variable, you have the opportunity to give it a good variable name, in case the R.id identifier is not good enough.

Also, method calls like ((Button) findViewById(R.id.button_english_splash)).someMethod are often not very readable as there are several parenthesis that are added.

I would recommend sticking to the first option. Perhaps not always, but mostly.

Other comments:

Remove // TODO Auto-generated method stub comments from your code
It is good that the onClick method has been marked with @Override.
Declare the onClick method inside the XML instead


integer log base 10 function without using java.lang.Math?

You have the possibility of an infinite loop.

Consider: logBase10Estimate(2147483647). Should be about 9.  We need a value of \$10^i\$ which is greater than 1000000000.  So, what values does x take on?

         10
        100
       1000
      10000
     100000
    1000000
   10000000
  100000000
 1000000000
 1410065408
 1215752192
 -727379968
 1316134912
  276447232
-1530494976
 1874919424
 1569325056
-1486618624
  :  :  :

Any value of num greater than 1000000000 is going to give incorrect results.  And some values, like 2147483647 will never give an answer, because no int value is greater than it, and x will never be odd, so it will never be equal to it either.

Not only is slepic's solution cleaner, it is correct and it terminates for all values.


There are some usability issues with @QuestionTags:

The ordering of tags matters. I think in the typical use case that's not the desired behavior
The input format is hackish (the implementation too) and unintuitive

I have an alternative suggestion that has different downsides:

Use multiple tag input fields, for example @Tag1, @Tag2, and so on
The advantage is that you could enter tags in any order, and without funky input rules
The disadvantage is that the number of tags you can enter will be limited to the number of fields you provide
Note that this approach will also open the possibility to choose the condition for for matching tags: they can be AND-ed or OR-ed. Your choice, or give another input to users to let them decide

The numbered fields are not exactly pretty, but I think the query will be easier to use this way. (Can be subjective.)

You could do similarly for matching keywords in the title.

Note that I dropped "Question" from the parameter names, to simplify to @TagN. On the network only questions can have tags, so this is obvious.

Other notes:

The semicolons at the end of variable declarations are unnecessary
It would be nice to make title optional
The repeated [Posts]. prefix of fields are not necessary, and a bit of a noise

Example implementation with some of the improvements explained above:

DECLARE @MinimumQuestionVotes INT = ##MinimumQuestionVotes:int?0##
DECLARE @MaximumQuestionAnswers INT = ##MaximumQuestionAnswers:int?0##
DECLARE @Tag1 NVARCHAR(50) = RTRIM(LTRIM(##Tag1:string? ##))
DECLARE @Tag2 NVARCHAR(50) = RTRIM(LTRIM(##Tag2:string? ##))
DECLARE @Tag3 NVARCHAR(50) = RTRIM(LTRIM(##Tag3:string? ##))
DECLARE @TitleContains NVARCHAR(250) = RTRIM(LTRIM(##TitleContains:string? ##))

SELECT
    Id AS [Post Link]
  , OwnerUserId AS [User Link]
  , Score
  , Tags
  , ViewCount
  , AnswerCount
  FROM Posts WHERE
        ClosedDate IS NULL
    AND PostTypeId = 1
    AND Score >= @MinimumQuestionVotes
    AND AnswerCount <= @MaximumQuestionAnswers
    AND (@Tag1 = '' OR Tags LIKE '%' + @Tag1 + '%')
    AND (@Tag2 = '' OR Tags LIKE '%' + @Tag2 + '%')
    AND (@Tag3 = '' OR Tags LIKE '%' + @Tag3 + '%')
    AND (@TitleContains = '' OR Title LIKE '%' + REPLACE(@TitleContains, ' ', '%%') + '%')
  ORDER BY Score DESC;


Testing whether lambda expression returns true for any list element

If you already have Common Lisp-derived functions in there, use CL-SOME instead:

(defun executable-in-path-p (executable)
  "Test if EXECUTABLE exists in path."
  (cl-some (lambda (path) (file-exists-p (concat (file-name-as-directory path) executable))) exec-path))

That's of course a little bit different than explicitly checking for t, but you shouldn't be doing that anyway in most cases (everything but nil is already true).


I see some things that could be improved.

Add comments to describe what the code is doing

It was not really immediately obvious what the code was intending to do.  In part this was because of some of the variable names, but also due to lack of comments.  Some comments describing what each function is attempting to do would have helped a lot.

Use mode rb for binary files

I found that the program did not work for me until I changed the file mode on the input from "r" to "rb".  This too made it not obvious which direction (base64 to text or vice-versa) was intended.  I'd expect the base64 file to be text mode and the binary file to be binary mode.

Allow the user to specify input and output files

The file names are currently hardcoded which certainly greatly restricts the usefulness of the program.  Consider using argc and argv to allow the user to specify file names on the command line.  Also OUTPUT.base64 is certainly a poor choice for a hardcoded file name since it is actually the input that is encoded in base64.

Avoid fprintf and friends for unformatted output

The code currently uses fprintf with a format string of "%c" for output of decoded byte values.  This isn't particularly efficient.  fputc would likely be a better choice for this.  Better still would likely be to decode multiple bytes and emit them all at the same time using fwrite.

Think carefully about where to put static data

In this code, the base64 static string is in the endecode() function, but it's only used within the enblock() function!  Wouldn't it make more sense to put it where it's being used and not have to pass the pointer?

Avoid magic numbers

One of the lines of code here is this:

fprintf(outputFILE, "%c", base64[((in[0] & 3) << 4) | ((in[1] & 240) >> 4)]);

All of those numbers, such as 240 and 4 no doubt mean something, but what?  I'm sure I could figure out that this is intended to mask and shift bits into place, but why make it a mystery?

Consider using buffering

In a program like this the typical bottleneck is I/O.  For that reason, one strategy for speeding up the program is to use memory (which is fast) in preference to disk I/O (which is triggered by such calls as printf and fread.  One way to apply that strategy in this case would be to read a larger chunk into memory, process it there and then write a large chunk of memory to disk at a time.  However, it's also often true that disk I/O is already buffered by the underlying operating system so the only way to find out for sure is to measure.


There's a few builtins you may have missed:

ymod2 = cycle [0,1]

If I read powersMac correctly, it basically goes along [0, 1, 0, -1] in cycles as well. So you can reformulate it as:

powersMac n = [0, 1, 0, -1] !! (n `mod` 4)

Considering that you only directly use it as powersMacList, we can again reformulate with cycle:

powersMacList = cycle [0, 1, 0, -1]

BTW: While we're on these two methods:

map (\y -> f y)

is equivalent to:

map f

Noticing that we can rewrite powersOfx as:

powersOfx = map (x^^) [0..]

firstLst does nothing. When there's a 0 in the one list, there's always a 0 in the other list as well.

The formatting in secondLst is somewhat confusing and difficult to read. Consider:

secondLst x = zipWith (*) (map fromIntegral powersMacList) (powersOfx x)

When you use factorial and run a map factorial [0..] you actually want the list of factorials. I'm stealing this excellent SO answer:

factorials = 1 : zipWith (*) factorials [1..]

which turns thirdList into:

thirdList x = zipWith (/) (secondLst x) factorials

applying everything we learned to maclaurin after discarding the fromIntegral calls (that are most likely a result of overspecific type signatures):

maclaurin n x = sum (take n (zipWith (*) (map (x^^) [0..]) (zipWith (/) powersMacList factorial)

Now putting it all together again, after giving out a bit more generous names than firstLst, secondLst and thirdLst:

factorials = 1 : zipWith (*) factorials [1..]

sinZeroDerivations = cycle [0,1,0,-1]
macRawElements x = zipWith (*) sinZeroDerivations (map (x^^) [0..])
macDiscounted x = zipWith (*) (macRawElements x) factorials

macResult n x = sum (take n (macDiscounted x))

Now if you wanted to be less maintainable you could inline the definitions again, but that's not really necessary, is it?

There's something about macDiscounted that annoys me a bit, namely that it only passes x through to macRawElements. We can fix that by swapping those two around like:

sinMacFactors = zipWith (/) sinZeroDerivations factorials

That allows us to specify a bit cleaner what we want:

macResult n x = sum (zipWith (*) (take n (map (x^^) [0..])) sinMacFactors)

notice the second argument to zipWith. That wants to be written as:

macResult n x = sum (zipWith (*) (map (x^^) [0..n]) sinMacFactors)


Handling multiple MassTransit response types

It's possible, providing c is your response from the bus, to do a lot of this without needing Reflection. Instead we can use a separate method and the joys of implicit typing to work out the type of TResponse for us.

Proposed solution

public IGenericResponse<TPayload> PublishRequest<TMessage, TPayload>(TMessage message, Type[] potentialResponseTypes)
        where TMessage : class
{
    IGenericResponse<TPayload> commandResult = null;

    _bus.PublishRequest(message, response =>
    {
        foreach (Type responseType in potentialResponseTypes)
        {
            var genericHandler = CreateHandler(response, message);
        }

        c.SetTimeout(10.Seconds());
    });

    return commandResult;
}

private GenericHandler<TResponse, TMessage> CreateHandler<TResponse,TMessage>(TResponse response, TMessage message)
{
    var handler = new Action<object>(result =>
    {
        commandResult = (IGenericResponse<TPayload>) result;
    });
    return new GenericHandler<TResponse, TMessage>(response, handler);
}


Increasing speed of Project Euler #14 - Longest Collatz Sequence

You have a bug. Try calling collatz(2) a few times and you'll see the result increment by one each time.

The source of trouble is initializing count to 1. It means you always add at least 1 to the memoized value. Note however that initializing count to 0 instead would give incorrect results when the loop terminates by the n != 1 condition.

You can avoid this bug and simplify your code at the same time: if you initialize collatz_counts to {1: 1} you can loop while n not in collatz_counts: and eliminate the if ... break.

Note also that an odd number is always followed by an even number in the sequence, so you can take two steps with  n = (n * 3 + 1) // 2

I suppose you are on Python 3 because you are using print(). Note that n/=2 is float division. n becomes a float which slows down subsequent calculations. Use n //= 2 instead.


Replacing an F# loop over a mutable variable by an immutable approach

I would write it this way

let rec exhaust m i =
    match m % i with
    | 0L -> exhaust (m / i) i
    | _ -> m

Not a huge improvement, but I think it's idiomatic. Now let's look at primeFactors:

let primeFactors x =
    let rec primeFactors' = function
        | (m, _, r) when m = 1L -> r
        | (m, i, r) ->
            let m' = exhaust m i
            primeFactors' (m', (i+1L), (if m <> m' then i::r else r))
    List.rev (primeFactors' (x, 2L, []))

Let's get rid of the when:

let primeFactors x =
    let rec primeFactors' = function
        | (1L, _, r) -> r
        | (m, i, r) ->
            let m' = exhaust m i
            primeFactors' (m', (i+1L), (if m <> m' then i::r else r))
    List.rev (primeFactors' (x, 2L, []))

And tidy up a little

let primeFactors x =
    let rec primeFactors' = function
        | 1L, _, r -> r
        | m, i, r ->
            let m' = exhaust m i
            primeFactors' (m', i + 1L, if m <> m' then i::r else r)
    primeFactors' (x, 2L, []) |> List.rev

I know the style in F# is for short variable names, and I'm all for that for the most part, but I think in this case we can/should make them a bit clearer.

let rec exhaust n factor =
    match n % factor with
    | 0L -> exhaust (n / factor) factor
    | _ -> n

let rec primeFactors' = function
    | 1L, _, factors -> factors
    | n, factor, factors ->
        let m = exhaust n factor
        primeFactors' (m, factor + 1L, if n <> m then factor::factors else factors)

let primeFactors n =
    primeFactors' (n, 2L, []) |> List.rev


How can I make this implementation of Euler's method more efficient?

Naming is confusing indeed. What is sy, om, etc?
I do not understand a need for eqDict and subVal. Using init directly is much more straightforward:

for example,

 result = [ init0[i] + h*f[i].subs(init0) for i in xrange(init0) ]
 init0 = [ x for x in result]

Updating subVal at the end of the function is meaningless.
It is very unclear why the Euler step is repeated 6 times for one time step.
Is there a reason to pass mesh, if the code only uses mesh[0]?
The description should mention that the function only addresses autonomous systems.


Search strings within a list from strings within a dictionary with the least complexity

both your datastructures can be cast into a dictionary directly:

>>> dict(newValue)
{'men': 'John Doe,Chris perry', 'women': 'Mary,Anne,Lita'}

>>> dict(keywords_list)
{'MEN': 'john,zack'}

from there you can just do a split based on , and compare in lowercase.