Method injection into TestClass local namespace for automatic generation of Python unittest "test_xxx" methods

I think your code is pretty good and you are following good practices with the exception to one (common mistake)

for name, datadict in data.items():
     fxnname = "test_data_{0}".format(name)
     fxn = lambda self, n=name, d=datadict: self.template_test_fxn(n, d)
     locals().update({fxnname: fxn})

Should be:

locals_ = locals()
for name, datadict in data.items():
     fxnname = "test_data_{0}".format(name)
     fxn = lambda self, n=name, d=datadict: self.template_test_fxn(n, d)
     locals_.update({fxnname: fxn})

This will prevent locals() from being evaluated when not necessary, but that's not even that big of a deal.

check out for another users use of locals https://stackoverflow.com/questions/8028708/dynamically-set-local-variable-in-python

i encourage other developers to review this, as it is a very interesting project.


Increase Perfomance of Nested Object Instantiation C#

Option 1) You can create a DataRelations between the two Data Tables and change the loop to fill in both classes at the same time.  This would require you do change the code that converts the results set into C# classes.  Microsoft has an example of GetChildRows and navigation here

Option 2) Otherwise you could also create a DataView and set the Sort property on the child Data Table and use FindRows method. Again will require you to change how you convert from datatable to C# classes.  I'd lean toward the first option instead of creating another set of data objects just for sorting.

Option 3) I'm guessing it will not be much better performance but you can try is using the Linq GroupJoin

foreach (var data in items.GroupJoin(usageItems,
    x => new {x.ItemCode, x.WarehouseCode},
    x => new {x.ItemCode, x.WarehouseCode},
    (itm, usg) => new
    {
        item = itm,
        usage = usg.ToList()
    }))
{
    data.item.Usage = data.usage;
}

Update #1 - Couple more options.

Option 4) Parallel the finding of data. Take Option 3 and add the AsParallel()

foreach (var data in items.AsParallel().GroupJoin(usageItems.AsParallel(),
    x => new {x.ItemCode, x.WarehouseCode},
    x => new {x.ItemCode, x.WarehouseCode},
    (itm, usg) => new
    {
        item = itm,
        usage = usg.ToList()
    }))
{
    data.item.Usage = data.usage;
}

I still think option 1 would be the best option as it will create a binary search tree for the relationship and give best performance.

Option 5) if you know the usageItems are sorted by the ItemCode and WarehouseCode you could just iterate over the list once and fill in the Item as it scans over the list.  This would be the most efficient but would require more complex code and also required that sort order is always correct.  While having this sort order would help Option 1 it wouldn't be required.


Questions
First to address some of your questions:

Would this sql work with all relational DB's that accept SQL?

No, it would not. In fact it's quite unrealistic (if not impossible) to write SQL queries that would port over to multiple DBMS, as they all have different syntax and different approaches. For example, row_number() over(order by u.Reputation desc) only works with Transact-SQL language, it would fail with syntax error on every other DBMS that I know of.
The best way to write queries that can port to multiple DBMS is to use a library/framework that supports it. For example, Python has SQLAlchemy and Java has Hibernate. These can adapt queries to the database being used.

If not, what is non-standard? How would I standardize it?

See (1) above. There's not really a "standard" per-se, it really depends on the DBMS and on the application code that uses it.

I don't like all-uppercase queries - I find them more difficult to read, so I used the lowercase, is that problematic?

No, it is not problematic. Just be consistent with whatever style you use.

Is it possible, in a standard way, to factor pieces out of this query? Or nonstandard way specific to SEDE (or other system)? For example, could I avoid doing lower(Location) repeatedly? What about aliasing my joined table outside the code block for usage inside of it? I have order by u.Reputation desc twice, for example, can I factor that out?

The nature of SQL makes it somewhat difficult to refactor parts of queries out. Most SQL engines support the creation of user-defined functions and/or procedures, which can help to simplify queries. In your case those calls to lower() and upper() are needed because SEDE has case-sensitivity enabled.

Review

from -- denormalize the Users with their Badges, i.e., flatten into a single table.
    Users u
  join
    Badges b

This from clause is a bit ugly. The aliases u and b are not very good names. It's a good habit to use meaningful names for aliases, which are meant to be identifiers rather than just a way to shorten the references. Here with having such short table names, an alias seems like overkill. It is also a good habit to use the as keyword and to specify the schema (although in the case of SEDE they are all the same schema, some other databases have tables organized in multiple schemes and it can become ambiguous).
from
    dbo.Users as usr
  -- denormalize the Users with their Badges, i.e., flatten into a single table.
  join dbo.Badges as bdg
    on usr.Id = bdg.UserId

[Rank] would make a better column name than [#].

Your order by clause at the end is redundant, you are already sorting in your row_number() clause, so no need to sort them again. orber by is expensive so you would want to limit the amount of ordering as much as you can.

We can extract the badge name and minimum reputation into variables:
declare @targetBadgeName nvarchar(50) = N'python';
declare @minimumReputation int = 1000;

And just use those in the query. You could also search multiple badges if you used a table variable and then just joined it.
I think it would be elegant to include the Gold, Silver and Bronze into the query if you want that as part of your result set. Note that this will decrease performance due to the min() aggregate and resulting group by clauses:
case min(bdg.Class)
  when 1 then 'Gold'
  when 2 then 'Silver'
  when 3 then 'Bronze'
  else 'unknown' end as [Highest Badge],

Now your result set will look like this:

Rank User Link               Reputation Highest Badge Location
---- ----------------------- ---------- ------------- ---------------------------
1    cletus                  368937     Bronze        New York, NY
2    Triptych                96145      Gold          NYC
3    Claudiu                 81412      Gold          New York, NY
4    Ben Hoffstein           59650      Bronze        New York, NY
5    Yuji 'Tomita' Tomita    59318      Gold          New York, NY
6    danben                  42686      Bronze        New York, NY
7    David Robinson          42489      Gold          New York, NY
8    Larry Lustig            33544      Bronze        New York, NY
9    Aaron Hall              32035      Gold          New York, NY, United States
10   chown                   31348      Silver        New York, NY

Finally, we can use a bit of SEDE magic to parametrize the query:
-- badgeName: Badge to search for:
declare @targetBadgeName nvarchar(50) = N##badgeName:string?python##;
-- minimumRep: Minimum reputation:
declare @minimumReputation int = ##minimumRep:int?1000##;

This will let you search other badges and different rep thresholds.

Everything combined (demo):
-- top users in NYC region for desired tag (default Python)
-- forked from Avinash Raj's query for Chennai

-- badgeName: Badge to search for:
declare @targetBadgeName nvarchar(50) = N##badgeName:string?python##;
-- minimumRep: Minimum reputation:
declare @minimumReputation int = ##minimumRep:int?1000##;

select
    row_number() over(order by usr.Reputation desc) as [Rank],
    usr.Id as [User Link],
    usr.Reputation,
    case min(bdg.Class)
      when 1 then 'Gold'
      when 2 then 'Silver'
      when 3 then 'Bronze'
      else 'unknown' end as [Highest Badge],
    usr.Location
from
    dbo.Users as usr
  -- denormalize the Users with their Badges, i.e., flatten into a single table.
  join dbo.Badges as bdg
    on usr.Id = bdg.UserId
where
    bdg.name = @targetBadgeName
  and
    usr.Reputation >= @minimumReputation
  and
    (
      lower(usr.Location) like '%nyc%'
      or upper(usr.Location) like '%NY, NY%'
      or lower(usr.Location) like '%staten%'
      or lower(usr.Location) like '%bronx%'
      or lower(usr.Location) like '%queens%'
      or lower(usr.Location) like '%new york, ny%'
      or lower(usr.Location) like '%manhattan%'
      or lower(usr.Location) like '%brooklyn%'
    )
group by
  usr.Id,
  usr.Reputation,
  usr.Location;


Here are some things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Once you remove that statement, you will have to add in the namespace where appropriate.  For example, fstream would be changed to std::fstream, endl to std:endl, etc.

Break up the code into smaller functions

In the current code, almost everything is done in main(). Rather than having everything in one long function, it would be easier to read and maintain if each discrete step were its own function.

Eliminate "magic numbers"

This code is littered with "magic numbers," that is, unnamed constants such as 0.004, 200, 25.0, etc.  Generally it's better to avoid that and give such constants meaningful names.  That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of "200" and then trying to determine if this particular 200 is one that needs to be changed or just some other constant that happens to have the same value.

Consider improving names

I think randnum is not a bad function name, but most of the variable names are single letter names that are not at all descriptive of what they're intended to represent.  More descriptive variable names would help readers of the code understand what it's doing.

Write results to the std::cout

Rather than have a single hard-coded file name, write the data to std::cout.  If the user then wants to save a copy, doing so is then a simple matter of command line output redirection.

Use <cmath> rather than <math.h>

Use the new style <cmath> rather than the C-style <math.h> for two reasons.  First, it is more idiomatic modern C++, but also because it uses namespaces.  Consistent with that, you shoud also use std::cos rather than just cos.  It's the same for log, pow and sin.

Don't use std::endl when '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.

Use only necessary #includes

The #include <functional> line is not necessary and can be safely removed.

Use constexpr where practical

In main, almost all of the variables are actually used as constants, so it would make sense to at least declare them as const and preferably constexpr if you're using a C++11 compliant compiler (and if you're not, you really ought to update your compiler).

Use objects

The purpose of the code is to simulate objects called particles.  It's written in C++.  Why doesn't the code use C++ objects named Particle?  Here's a Particle class we can use:

class Particle {
public:
    Particle() : x_{0}, y_{200}, phi_{0} {}
    Particle &operator++();
    double phi() const { return phi_; }
public:
    static double get_dr();
    void next(const Particle &other);
    bool bad() const;
    double x_;
    double y_;
    double phi_;
};

Now main can look like this:

int main() {
    constexpr int N{10000};
    std::vector<double> J(N, 0);
    constexpr int numParticles{1000};
    std::vector<Particle> particles(numParticles);

    for (auto &step : J) {
        for (auto &p : particles) {
            ++p;
            step += std::cos(p.phi());
        }
        std::cout << step / numParticles << '\n';
    }
}

Isn't that nice?

Simplify the mathematics

Let's look at how the class functions above are implemented.  First is the operator++:

Particle &Particle::operator++() {
    Particle testp;
    for (testp.next(*this); testp.bad(); testp.next(*this))
    { /* do nothing */ }
    return *this = testp;
}

This has the effect of the inner loop in the original code.  The next function is this:

void Particle::next(const Particle &other) {
    double dr = get_dr();
    phi_ = randnum(0, M_PIl);
    x_ = static_cast<int>(other.x_) + std::cos(phi_) * dr;
    y_ = static_cast<int>(other.y_) + std::sin(phi_) * dr;
}

The get_dr function is this:

double Particle::get_dr() {
    constexpr double a = 1.0;
    constexpr double b = 25.0;
    constexpr int alph = 0;
    constexpr double B = (alph < 1.01 && alph > 0.99) ?
        1 / (std::log(b) * std::pow(b, 1 - alph) - std::log(a) * std::pow(a, 1 - alph))
       : (1 - alph) / (std::pow(b, (1 - alph)) - std::pow(a, (1 - alph)));
    return std::pow(std::pow(a, 1 - alph) + randnum(0, 1) * (1 - alph) / B, 1 / (1 - alph));
}

Finally the simple version of bad() is this:

bool Particle::bad() const {
    constexpr int H = 500;
    constexpr int h = 200;
    constexpr double C = 0.004;
    constexpr double A = 0.002;
    constexpr double Delta = 1 / 7;
    return
        (std::sin(A * x_) + Delta * std::sin(C * x_) / 2) * h + H < y_;
}

However, the maximum value of sin is 1, so the upper bound of the left hand side of that inequality can be expressed as a constant.  Since comparing against a constant is usually much faster than invoking std::sin we can use this knowledge as follows:

bool Particle::bad() const {
    constexpr int H = 500;
    constexpr int h = 200;
    constexpr double C = 0.004;
    constexpr double A = 0.002;
    constexpr double Delta = 1 / 7;
    constexpr double maxval = (1 + Delta * 1 / 2) * h + H;
    return maxval < y_ ||
        (std::sin(A * x_) + Delta * std::sin(C * x_) / 2) * h + H < y_;
}

The short circuit expression evaluation means we only invoke the computationally expensive sin function is the comparison against maxval fails.  Testing on my machine shows that this makes the program about 20% faster.  You could squeeze out still more time by noting that x need only be calculated if the first test fails.  Generally, you want to arrange things so that simpler tests are done first.

It may be advantageous to look at using a different coordinate scheme (polar vs. rectangular for instance) if the resulting equations simplify.  I suspect they might.


Generics

Generics... you want them. In your solution, they would be relatively easy to apply too. Consider your Node class:

class Node {
  Object data;

  Node next;

  public Node(Object item) {
    data = item;
  }

  public Node(Object item, Node n) {
    data = item;
    next = n;
  }
}

Now, that Node only works on Object values, but you want it to be an Integer. Using generics, this is a treat (while we are at it, we will make data and next private and final, and add getters for them...):

class Node<T> {

  private final T data;
  private final Node<T> next;

  public Node(T item) {
    data = item;
  }

  public Node(T item, Node<T> n) {
    data = item;
    next = n;
  }

  public T getData() {
    return data;
  }

  public Node<T> getNext() {
    return next;
  }

}

There, now Node is self contained, immutable, and generic. It can contain any object type, just specify the type you want when you construct it, for example:

Node<Integer> node = new Node<>(10);

Applying the same logic to your Stack class, we get:

class Stack<T> {
  Node<T> top;

  T pop() {
    if (top != null) {
      T item = top.getData();
      top = top.getNext();
      return item;
    }
    return null;
  }

  void push(T item) {
    Node t = new Node(item, top);
    // commented out, make Node immutable, pass in as constructor
    // t.next = top;
    top = t;
  }

  T peek() {
    return top.getData();
  }

  boolean isEmpty() {
    if (top == null) {
      return true;
    }
    return false;
  }
}

Right, that makes it generic, there are still a bunch of problems... but, it can be easy to use with:

Stack<Integer> stack = new Stack<>();

With the above stack, you should not need any casts from Object to Integer

Simplifications

Now, looking at some other parts of your code, let's simplify...

Chained constructors: whenever possible, have just one constructor that "does stuff" for your class, and have your other constructors call the main one. Your constructors look like:

  public Node(Object item) {
    data = item;
  }

  public Node(Object item, Node n) {
    data = item;
    next = n;
  }

Note that they both access the data = item item directly. It would be better to change your first constructor to be:

  public Node(T item) {
      this(item, null);
  }

The above constructor calls the second one with a null value.

Boolean expressions are boolean. If statements test a boolean condition. Why do both?

  boolean isEmpty() {
    if (top == null) {
      return true;
    }
    return false;
  }

This is a good one, it can be simply:

boolean isEmpty() {
  return top == null;
}

The push can be simplified too:

  void push(T item) {
    Node t = new Node(item, top);
    // commented out, make Node immutable, pass in as constructor
    // t.next = top;
    top = t;
  }

That can be simply:

  void push(T item) {
    top = new Node(item, top);
  }

Note that there is no need for the one-argument constructor now in the Node class.

Code duplication is always a red flag. Consider the following methods:

  public void printStack() {
    Node current = stack.top;
    while (current != null) {
      System.out.println(current.data);
      current = current.next;
    }
  }

  public void printAuxiliaryStack() {
    Node current = auxiliaryStack.top;
    while (current != null) {
      System.out.println(current.data);
      current = current.next;
    }
  }

Why have the method twice, when instead you can have just:

  public void printStack(Node<T> current) {
    while (current != null) {
      System.out.println(current.getData());
      current = current.getNext();
    }
  }

Now, you can call that method with either the stack or the auxilliaryStack top nodes... but, that method really belongs on the stack itself, not outside the stack. Move it to the stack, and it becomes:

  public void printStack() {
    Node<T> current = top;
    while (current != null) {
      System.out.println(current.getData());
      current = current.getNext();
    }
  }

Now you can simply do:

stack.printStack();
auxilliaryStack.printStack();

Bugs

The following is a bug:

  Object peek() {
    return top.data;
  }

What if the stack is empty? You will get a NullPointerException!

Instead, do:

  T peek() {
      return top == null ? null : top.getData();
  }

Sorting

Your algorithm looks sane, but the interface is ... cumbersome. You have a stack, and auxilliaryStack declared as members of the Solution class. Now, the rules of object orientation indicate that the data should be encapsulated. There are two logical ways to implement the sort that I can see. The one is to have a static method that takes a Stack as input, and sorts it in place (creating a temporary, and method-private auxStack to sort with). The other solution adds the sort method to the Stack class itself (and also has an internal auxStack). The second route is the better one.

public void sort() {
    if (isEmpty()) {
        return;
    }
    Stack<T> auxStack = new Stack<>();
    .....
}

I recommend you make the changes and see how it works out for you. You will find that the logic and flow of the structure is neater, and more manageable.


If you're determined to avoid using a module for this, how about something like the following:

my %config;
while (my $line = <$configfh>) {
    chomp $line;  # Strip trailing linefeeds, you probably don't want them there
    my @fields = split(/\s+/, $line);
    $config{$fields[0]} = $fields[1] if $fields[0];
}

But perhaps your config file may contain values with whitespace? If you can require those to be wrapped in quotes, or some other convenient character, that's not a problem.

my %config;
while (my $line = <$configfh>) {
    chomp $line;
    my ($field, $value) = split(/\s+/, $line, 2);  # The 2 is how many parts to split into
    if ($value =~ /^\"/) {
        $value =~ s/^\"(.*?)\"/$1/;  # Keep what's in the first pair of quotes
    } else {
        ($value, undef) = split(/\s+/, $value);  # Drop trailing comments
    }
    $config{$field} = $value if $field;
}

(Note that the " characters don't actually need escaping, but the syntax highlighting breaks otherwise...)

Obviously there are other possible cases which this doesn't cover, but if your use cases are that extensive, you should probably reconsider and use a module.


How to keep current HtmlElement active and change its properties?

There are some repetitions in the current implementation, which can be refactored and the code will become clearer. For example:

Use a custom type or interface for the private members.

interface MyPoint { // of course, choose a better name than MyPoint, which matches your context!
  element: HTMLElement;
  pointMeter: Point;
}

export class Kizda {
  private point1: MyPoint;
  private point2: MyPoint;

  ...
}

The createPoint function produces only a part of the point object, but it can indeed produce instances of MyPoint. And it does not need to be nested inside the action function:

private createPoint(e: MouseEvent, color: string): MyPoint {
  const size = '12px';
  const element = document.createElement('div');
  const style = element.style;

  style.position = 'absolute';
  style.width = size;
  style.height = size;
  style.background = color;
  style.borderRadius = '50%';

  this.setCoordinates(element, e);

  document.body.append(element);

  const pointMeter = this.getMouseMPoint(e);
  return { element, pointMeter };
}

private setCoordinates(point: HTMLElement, e: MouseEvent): void {
  const style = point.style;
  style.left = `${e.x}px`;
  style.top = `${e.y}px`;
}

Finally, adjust the implementation of the action method by reusing the refactored items:

public action(e: MouseEvent): void {
  if (!this.point1) {
    this.point1 = this.createPoint(e, 'red');
  }
  else if (!this.point2) {
    this.point2 = this.createPoint(e, 'green');
  }
  else {
    this.setCoordinates(this.point2.element, e);
  }
}


A modification of @Jerry's answer:

#pragma once

#if __has_include(<optional>)

#   include <optional>
namespace stdx {
  using namespace ::std;
}
#elif __has_include(<experimental/optional>)
#   include <experimental/optional>
namespace stdx {
  using namespace ::std;
  using namespace ::std::experimental;
}

#else
#   error <experimental/optional> and <optional> not found
#endif

this has the advantage that the same namespace can be used for all "experimental" features (stdx).

So stdx::optional and stdx::variant both work.

We have to only using namespace ::std::experimental; after at least one <experimental/ header is included, as if it does not exist that is ill formed, and introducing one ourselves also makes the program ill formed.


Python traverse a directory recursively and print contact numbers

You don't need a class here at all. You only seem to use it as a namespace and for that just importing it from another file would be sufficient.

I would make pattern a global constant and give it a better name.

I would put the extracting of the phone numbers into a separate function for readability.

I would make both functions generators and make it the responsibility of the caller to actually print the contact (or do something else with it).

Lastly, I would use a if __name__ == "__main__": guard to allow importing these functions without executing the traversal.

import os, re class

PHONE_NUNBER = re.compile('^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$')

def get_contacts(filename, pattern):
    with open(filename) as fn:
        for contact in fn:
            if pattern.match(contact):
               yield contact

def get_contacts_recursive(dir_path, pattern):
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            filename = os.path.join(root, file)
            for contact in get_contacts(filename, pattern):
                yield contact

def main():
    for contact in get_contacts_recursive('/home/sinscary/Documents/niki', PHONE_NUMBER):
        print contact

if __name__ == "__main__":
    main()


Lexicographically smallest wave like array without sorting

I don't think this could be done without sorting, but there are a couple of aspects that can be improved with the current code. First of all, there is code duplication; the part

temp = a.get(i);
a.set(i, a.get(i-1));
a.set(i-1, temp);

is duplicated between the two branches of the code. A first step would be to suppress that duplication. There are several approaches, like merging the two if statements in a single one with

if (i%2 == 0 && a.get(i) < a.get(i-1) || i%2 == 1 && a.get(i) > a.get(i-1))

but it becomes a bit unclear. Another approach would be to factor that into a swap method, that swaps two indexes of a list... and you actually don't need to write one, because it already exists! You can just have:

Collections.swap(a, i, i - 1);

without having your own temporary variable.

But there is an even simpler approach: since the list was sorted in ascending order before hand, the result can be found directly by swapping the items two by two. It makes sure that the result is the smallest lexicographically (thanks to the sort) and that each item verify the condition (thanks to the swap). So instead of having an index i going over the number and increasing by 1, have it increase by 2 and always swap i with i + 1.

for (int i = 0; i < a.size() - 1; i += 2) {
    Collections.swap(a, i, i + 1);
}

This takes care of 2 problems at once:

There is no need for any if checks with regard to the parity of i: by construction of the loop, it will always be even, so the loop will swap an element with the element after it, and then go to the next unswapped element.
It also fixed the duplication issue.

Note that the loop needs to go to a.size() - 1 because we're increasing by steps of 2, and an odd number of elements shouldn't cause problems.

if (a.size() == 0 || a.size() == 1)
  return a;

Instead of checking if the size is 0, use isEmpty() which is cleaner. But actually, you don't need those early-returns to begin with, since the rest of the code handles them fine without any overhead (the for loop won't be executed, and the method will return directly). You can safely remove them.

public ArrayList<Integer> wave(ArrayList<Integer> a)

You should make the methods as generic as they can be:

Don't code against ArrayList. What if the user wants to pass another type of list? For example, consider the following:

wave(Arrays.asList(1, 2, 3, 4, 5))

This won't compile because the given list is not an ArrayList. This should be perfectly safe to do, even though asList returns a fixed-size list, the method is not going to add or remove elements from it, just sort and swap values. Therefore, switch to using the general List:

public List<Integer> wave(List<Integer> a)

That also forces the user to want to wave only lists of integers. What if they want to sort longs?

public <T extends Comparable<? super T>> List<T> wave(List<T> a)

would enable that use-case. The elements have to be comparable so that the constraint "a1 >= a2 <= a3 >= a4 <= a5" is possible, so adding extends Comparable makes sense.
The method actually modifies in-place the given list. It does not return a new list, but updates the given list. I would make the method not return the updated list as well. If the method returns something, the user probably expects it to return a new object, not to modify the given argument. Therefore, when the method does modify its argument in-place, don't return it; it makes it clear that the method is doing this in-place modification. The JDK utility methods do this as well (for example in the Collections or Arrays classed).


Fast canonical indexing of elements in array

First, why return a vector of characters when the output data is clearly about integers? Instead of initializing

output <- input

i.e., a vector of the same class as input (character), you should have used:

output <- integer(length(input))

to pre-allocate a vector of integers. Integers use less memory; you will also save time avoiding unnecessary conversions from integer to character.

Second, grep is for regular expression matching. When you do grep("a", x), you are checking if x contains an "a" which is not the same as asking if x is exactly "a". In your case, you want exact equality so having used == in output[input == labels[i]] <- i would have been more appropriate. Even better, there is the match function. It is vectorized so you can avoid the for loop and just do:

canonical2 <- function(input){
   labels <- unique(input)
   match(input, labels)
}

Last, you could look into factors. Your code is equivalent to doing:

canonical3 <- function(input) {
   labels <- unique(input)
   as.integer(factor(input, levels = labels))
}

Comparing speeds:

library(microbenchmark)
input <- sample(letters, 1e4, replace = TRUE)

identical(as.integer(canonical(input)), canonical2(input))
# [1] TRUE
identical(canonical2(input), canonical3(input))
# [1] TRUE

microbenchmark(canonical(input), canonical2(input), canonical3(input))

# Unit: microseconds
#               expr       min         lq     median         uq       max neval
 #  canonical(input) 47669.384 49870.0695 51615.3475 53604.0700 65261.986   100
#  canonical2(input)   492.921   529.9210   589.2805   635.7925   966.853   100
#  canonical3(input)   526.412   582.8405   638.5455   718.9310  3821.143   100


Handling multiple IO operations that return optional values

Here's how your pseudocode can be rewritten with bounded indentation using MaybeT.

action state pool (Authenticated _) id = cached <|> retrieve <|!> throwError err404 where
  cached = snd <$> MaybeT (find id <$> fromState state)
  retrieve = do
    doc <- performOp <$> MaybeT (getDocumentFromId id pool)
    _ <- lift $ saveToState state doc
    return doc

infix 2 <|!>
(<|!>) :: Monad m => MaybeT m a -> m a -> m a
mx <|!> y = runMaybeT mx >>= maybe y pure


Your main issue is (as you've already noticed) one of code repetition. Some simple helper methods here will do the trick; caveat - untested:

from flask import Flask, render_template, request, url_for, jsonify
from ciphers import RSA, DES
from prime import generate_semiprime_number as gspn

app = Flask(__name__)
get_form = None

@app.route('/')
def index():
    return render_template('index.html')

def do_rsa(encrypting):
    global get_form

    direction = 'en' if encrypting else 'de'
    tmpl = f'rsa_{direction}crypt.html'

    if request.method == 'GET':
        return render_template(tmpl, gf=True)

    kwargs = {'p': request.form.get('p'),
              'q': request.form.get('q'),
              'e': request.form.get('e')}
    if encrypting:
        rsa = RSA(request.form.get('pt'), **kwargs)
    else:
        ct = [int(x) for x in request.form.get('ct')[1:-1].split(',')]
        rsa = RSA(ciphertext=ct, **kwargs)

    kwargs = {}
    if encrypting:
        kwargs['gpsn'] = gpsn
    return render_template(tmpl, gf=False, rsa=rsa, **kwargs)

@app.route('/rsa_encrypt', methods=('GET', 'POST'))
def RSA_enc():
    return do_rsa(True)

@app.route('/rsa_decrypt', methods=('GET', 'POST'))
def RSA_dec():
    return do_rsa(False)

def do_des(encrypting):
    global get_form

    direction = 'en' if encrypting else 'de'
    tmpl = f'des_{direction}crypt.html'

    if request.method == 'GET':
        return render_template(tmpl, gf=True)

    kwargs = {'user_key': request.form.get('key')}
    if encrypting:
        des = DES(request.form.get('pt'), **kwargs)
    else:
        des = DES(ciphertext=request.form.get('ct'), **kwargs)

    return render_template(tmpl, gf=False, des=des)

@app.route('/des_encrypt', methods=('GET', 'POST'))
def DES_enc():
    return do_des(True)

@app.route('/des_decrypt', methods=('GET', 'POST'))
def DES_dec():
    return do_des(False)

@app.route('/gpsn', methods=('POST',))
def _gpsn():
    return jsonify({'result' : str(gspn(request.form['bits']))})

if __name__ == '__main__':
    app.run()


Hashing array of strings as Merkle tree in one function

In my opinion this statement is quite complicated to read, compared to what you want achieve:

int nextSize = currentSize % 2 == 0 ? currentSize / 2 : (currentSize + 1) / 2;

You could consider using some brackets:

int nextSize = (currentSize % 2 == 0) ? (currentSize / 2) : ((currentSize + 1) / 2);

Or just use Math.ceil():

int nextSize = (int) Math.ceil(currentSize / 2.0))

Furthermore you are computing hashes.size() twice per loop:

while(hashes.size() > 1)
{
    int currentSize = hashes.size();
    // ...

you could write:

int currentSize = hashes.size();
while(currentSize > 1)
{
    currentSize = hashes.size();
    // ....

instead.

Other than that your code looks fine to me, besides strs is not the best name for a parameter. You could rename it to improve readability and usability.


Newton-Pepys, common birthdays and other probability simulations in Python 3

1. Design

I think that using the @mean_of_experiments decorator is not the best approach to this problem:

There might be cases where you want to run the underlying function by itself, for example in order to test it, but the decorator prevents this.
You have to choose the number of experiments, N, when you define the function. This is restrictive: it means that you can't run the function with different values of N.
The only result you get back is the mean. But what if you sometimes want another statistic, such as the standard deviation?

My preferred design would use the principle of separation of concerns. For example, we might write:

def mean_of_experiments(n, f, *args, **kwargs):
    "Return the mean of n calls to f(*args, **kwargs)."
    return mean(f(*args, **kwargs) for _ in range(n))

This meets all my objections:

I can call common_birthday(23) to carry out one experiment, or mean_of_experiments(1000, common_birthday, 23) to find the mean of 1000 experiments.
I can choose a different value of n for each call to mean_of_experiments, I don't have to commit to a particular value in advance.
If I need the standard deviation, I can write std_of_experiments, and this can coexist in the same program with mean_of_experiments.

2. Review

The code is very clear and well documented! In the top 1% of questions on Code Review.
If you're going to use NumPy at all, I think you might as well take advantage of it everywhere, instead of mixing and matching with the Python standard library. For example, in common_birthday you could use numpy.random.randint and numpy.unique:

def common_birthday(k, days=365):
    "Return True iff there are any repeats among k random birthdays."
    return k != np.unique(np.random.randint(1, days, size=k)).size

Similarly, in matching, you could use numpy.random.permutation, numpy.arange, and numpy.any:

def matching(k=52):
    """Return True iff there's any j such that card j appears in the j'th
    place of a shuffled deck of k cards.

    """
    return (np.random.permutation(k) == np.arange(k)).any()

The docstring for boardings doesn't explain the meaning of the scale and N arguments.
The scale argument to boardings seems unnecessary, since the randomly chosen instants will scale along with the arrival times.


How many?

How many primes are there less than N?

The short answer is that you should have somewhere between 100,000 and 1,000,000 entries in the array.  There's a table that says that there are less than 10,000 primes before 100,000.

        int limit = Integer.MAX_VALUE / 10;

You can calculate this based on N.  So assuming you pass N as a parameter to the method:

        final int LIMIT = 2 * N * (int)Math.log(N);

Would contain the necessary number of primes consistently.  You could probably get away with a considerably smaller number than 2.  E.g. 1.1 would likely also work.

I made LIMIT final and capitalized it.  It's not going to change, so we may as well make note of that.

Match name to function

        boolean primes[] = new boolean[limit];

You call this primes, but the prime values are false.  I would change this to composites.  Then it makes more sense for false to mean that it is prime.  You may even want to call it something like compositeStatuses or factorableStatuses to make that meaning clearer.

Optimize

            for(int j = i; j < limit; j += i){

You can actually do fewer than this:

            for (int j = i * i; j < LIMIT; j += i) {

This works because the first i multiples will have already been marked false by previous primes.  For example, when i is 2, then this starts at 4.  For 3, this starts at 9.  The only multiple between 3 and 9 is 6 which was marked false when i was 2.  In general, if a multiple is less than i * i, it will have been seen previously because it must be a multiple of i and something smaller than i.  All primes smaller than i have already been found.  The i * i value is the first multiple that we've never seen previously.

I added some extra spaces for readability as well.

Readability

        while(primeList.size() <= 10001){
            while(true){
                if(primes[i] == false){
                    primeList.add(i);
                    break;
                }
                i++;
            }

            for(int j = i; j < limit; j += i){
                primes[j] = true;
            }
            i++;
        }

I would find this easier to read as

        for (int i = 2; i < LIMIT; i++) {
            if (composites[i] == false) {
                primeList.add(i);
                if (primeList.size() >= N) {
                    break;
                }

                for (int j = i * i; j < LIMIT; j += i) {
                    composites[j] = true;
                }
            }
        }

This also explicitly handles the case where you try to go past the end of the array.  And it returns just N primes.  The original code would return 10,002 primes when you only needed 10,000.

I find it easier to follow without the infinite loop.  Now we can see that we are iterating from 2 to LIMIT checking if each value is prime.  There's only one loop that changes i so it's easy to understand what happens on each iteration.


/**
 * @param $strength
 * @param $password
 * @return bool
 */
public function is($strength, $password)
{
    $method = sprintf("is%s", ucwords($strength));
    return call_user_func([$this, $method], $password);
}

This is not okay.

You're taking user input... (or something that I assume to be user input...) and then looking for a method in your own class, and then executing it. This whilst you know or at least can reasonably assume that you know which values the user input might contain.

So let's nuke it.

If we nuke it, then we need a new implementation here.

/**
 * @param $field
 * @param $password
 * @param Arguments $args
 * @return mixed
 */
public function validate($field, $password, Arguments $args)
{
    $type = $args->getVariables();

    if ($type && $type != self::NORMAL) {
        return $this->is($type[ 0 ], $password);
    }

    return $this->isNormal($password);
}

Well, we can use a switch. See also the documentation here: http://php.net/manual/en/control-structures.switch.php (I'm not familiar with PHP syntax, but you should understand the gist of the idea.)

/**
 * @param $field
 * @param $password
 * @param Arguments $args
 * @return mixed
 */
public function validate($field, $password, Arguments $args)
{
    $type = $args->getVariables();

    if ($type && $type != self::NORMAL) {
        switch ($type [ 0 ]) {
            case self::NORMAL:
                return $this->isNormal($password);
                break;
            case self::MEDIUM:
                return $this->isMedium($password);
                break;
            case self::STRONG:
                return $this->isStrong($password);
                break;
        }
    }

    return $this->isNormal($password);
}

Lastly, I'd say you should reorder your methods so they are ordered as "normal", "medium" and "strong" in the code as well. It reads better.


Shortest and longest city name and alphabetical order

Formatting

Your SQL statement formatting is not very good. I would encourage you to use a free tool like sql-format.com (or one of the many others) to format your SQL queries in a more readable way. This is your original query, with better formatting (I indented the subqueries by hand because the tool didn't).

SELECT
    city,
    CHAR_LENGTH(city)
FROM STATION
WHERE city = (
    SELECT
        MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
        SELECT
            MIN(CHAR_LENGTH(city))
        FROM STATION
    )
)
OR city = (
    SELECT
        MIN(city)
    FROM STATION
    WHERE CHAR_LENGTH(city) = (
        SELECT
            MAX(CHAR_LENGTH(city))
        FROM STATION
    )
);

Now we can see much more easily how deeply nested queries are.

Variables

You could make the code simpler by using a few user-defined variables:

SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);
/* Query below only to demonstrate the variables */
SELECT
  '@MinCityLen' AS `VariableName`,
  @MinCityLen AS `Value`
UNION
SELECT
  '@MaxCityLen',
  @MaxCityLen;

Which returns this:

VariableName  Value
@MinCityLen   3
@MaxCityLen   4

This will abstract away one level of nesting and make the query simpler to understand. Note that the @ symbol is just a convention, it is not needed as far as MySQL syntax goes. Some database systems do require the @ symbol though, the most famous being Microsoft SQL Server.

Shorter code != Better code

Sometimes, better code is longer rather than shorter. This is often the case with SQL. Longer code can be better formatted, better documented, better abstracted, better structured. In my personal SQL experience, short queries, unless they are very simple, are often pretty bad. Yours is not a case of a very simple query.

This is what I came up with. I also have a link on sqlfiddle

# find shortest city name
SET @MinCityLen = (SELECT MIN(CHAR_LENGTH(city)) FROM STATION);
# find longest city name
SET @MaxCityLen = (SELECT MAX(CHAR_LENGTH(city)) FROM STATION);

SELECT
    city,
    CHAR_LENGTH(city)
FROM
    STATION
WHERE
    # find shortest city name sorted alphabetically
    city = (
        SELECT
            city
        FROM STATION
        WHERE CHAR_LENGTH(city) = @MinCityLen
        ORDER BY city ASC
        LIMIT 1
    )
    # find longest city name sorted alphabetically
    OR city = (
        SELECT
            MIN(city)
        FROM STATION
        WHERE CHAR_LENGTH(city) = @MaxCityLen
        ORDER BY city ASC
        LIMIT 1
    );


Implementing printf to a string by calling vsnprintf twice

Looks reasonable to me.

The efficiency of this code really depends on your expected workload. For example, if you're expecting to use this code with a lot of strings of length 50 to 60, and you don't mind wasting a bit of memory in the case that the strings are shorter, then you could probably avoid a vsnprintf in the common case by writing

string string_printf(const char *fmt, ...) {
    va_list in, copy;
    const int INITIAL_SIZE = 60;
    string a = string_new_size(INITIAL_SIZE);

    /* start the main input */
    va_start(in, fmt);
    /* make a copy of the input */
    va_copy(copy, in);

    /* run vsnprintf just to see how much bytes needed */
    int length = vsnprintf(a, INITIAL_SIZE, fmt, copy);
    va_end(copy);

    /* allocate the amount now */
    if (length >= INITIAL_SIZE) {
        /* re-run */
        a = string_new_size(length+1);
        int new_length = vsnprintf(a, length+1, fmt, in);
        assert(new_length <= length);
    }
    string_to_sr(a)->len = length;
    va_end(in);

    /* done */
    return a;
}

Notice that I've also changed your size = ... + 1, size-1 to length = ..., length, on the principle that adding and subtracting 1 all the time is less efficient than not adding and subtracting 1 all the time; and on the principle that everybody knows what "string length" means (it's strlen), whereas "string size" is a bit ambiguous (does it include the null terminator or not?).

Somewhat off-topic: I'm leery of your use of string a; to declare a pointer. To me, a bare identifier always means "value-semantic object", as in FILE or char; and if the object is supposed to have pointer semantics, you add a star, as in FILE* or char*. Hiding the star inside a typedef strikes me as a bad idea. Although I admit that if you're coming from Java or Objective-C or Python or any other non-C, non-C++ language where

a = b;

traditionally means "don't copy the value, just reseat the pointer a to point to the same heap object as b", then your use of string a; a->something(); will seem perfectly natural. To me it seems confusing; I'd rather write string *a; a->something();.


Is Load Day?
Your IsLoadDay function seems a little overcomplicated.
Might I suggest trying something along the lines of this, which brings all the checks you want to do pretty nicely into a single coalesce:
CREATE FUNCTION [dbo].[IsLoadDay](@Dt DATE)
RETURNS BIT
AS
BEGIN

RETURN COALESCE
(
    --If it is a monday or sunday, it's not a load day
    CASE WHEN DATENAME(DW, @Dt) IN ('SUNDAY', 'MONDAY') THEN 0 END,

    --If it is a designated not load day, it's not a load day
    (
        SELECT 0
        FROM [DBMGMT].[dbo].[afrs_daily_load_no_load_date]
        WHERE [load_date] = @Dt AND [load_ind] = 'N'
    ),

    --If it is a holiday, it's not a load day
    (
        SELECT 0
        FROM [master].[dbo].[HOLDY_WA_STATE]
        WHERE [HOLDY_DATE] = @Dt
    ),

    --Otherwise, it's a load day
    1
)
END
GO


Since this is a single-translation-unit program, mark your panic and help as static.
About this:
(whoami = strrchr(progName, '/')) ? ++whoami : (whoami = progName);

"Yikes". Generously we call this write-only code. Unroll it to
char *whoami = strrchr(progName, '/');
if (whoami)
    whoami++;
else
    whoami = progName;

In this loop, your i declaration should be moved down:
for(unsigned int arg = 1, i = 0; arg < argc; ++arg){
    for(i = 0; i < (unsigned int)__NUM_OF_ELEMENTS(args); ++i){

should be
for (unsigned int arg = 1; arg < argc; ++arg) {
    for (int i = 0; i < (unsigned int)__NUM_OF_ELEMENTS(args); ++i) {

to narrow its scope.
Don't use goto. Factor out a function where the double loop termination is done using a return.


Advice 1

Instead of having checkRow, checkCol and checkSquare, I suggest you allocate a simple char array for each row, column and minisquare:

char visited[10];

You initialize each visited[0], ..., visited[9] to zero. Next, when you put a number in an empty cell, you mark it in three such "sets": current column, current row and current minisquare. This arrangement will bring the complexity of checking each row, column and minisquare from \$\Theta(d)\$ to \$\Theta(1)\$, where \$d\$ is the width/height of the input sudoku board.

Advice 2

What comes to the actual algorithm, I suggest you use recursion/backtracking. That will clean your code quite a bit, and will allow you better adapting it to, say, \$4 \times 4\$ or \$16 \times 16\$-sudokus.

The idea is as follows. You march through the board rows, each row from left to write. You leave the cells that have a predefined value as is, but you put 1 to the first empty cell, and recur to the next cell. If 1 does not belong, you try 2, 3 and so on. Once you have found a valid value, move to the next empty cell. At some point it might happen than none of the numbers fit. In such a case you go one step backwards (backtracking) and try increment the previous value. If you can translate from Java, see this, starting from line 163.


A set of queries in PHP to show occupancy of various cabins

There is nothing wrong with using multiple queries. Three simple queries versus a single, convoluted monster query. Guess which option will cause you the least problems long term?

You get the extra overhead of parsing three queries, but, its about the same amount of work for the DBMS to get the data in both cases.

Also I think you should consider holding your images in separate files and just hold the file names in the database. You can then use HTML "<image>" tags to reference these. This will make the images "cache"able on the client side, and, will move the work of retrieving the images to the web server, which is much more efficient and will allow for a degree of parallelism when loading the users page.


Algorithm to say if win or lose using player's rating and randomness

World Chess Ratings are going to be skewed: people that lose are less likely to play than people who win, so it's quite possible that everyone who went to a single tournament and got wrecked is not going to play in tournaments anymore. And Elo is a measurement of skill, not skill itself, so of course it won't go past a certain value. A good chess player who played 1 competitive match has a lower rating than his playing strength. So even though his rating is lower, he'll win more than his rating suggests, that's why his rating goes up.

As such, your simulation is going to keep giving skewed results until you give each player a "skill" attribute which determines their real playing strength. That means each player would have a rating (which starts at 1000) and a skill (which starts at a randomized value between 0 and 2500 or so, where the distribution is, say, Gaussian), and where you used to compare rating, you compare skill instead. This should give you a more realistic simulation of Elo rating, but you'll still be assuming that players all play equally as much (which is not the case in real life).


Is this efficient if I only use it for small inputs?

For small inputs, anything is efficient.
For big data, having each Node as such a large object would be inefficient.
I depends what kind of actions you would do over the graph. If you access it sequentially, there can be also a linked implementation like:

class LinkedNode {
    public Node firstChild;
    public Node nextSibling;
    boolean visited;
}

Here's an alternative, without objects but with arrays instead:

int[] edgeWeights;
int[] edgeIndicies;

At the begin, edgeIndicies will have values [0,1,2,...n].
Sorting the weights, you move the indicies instead, so if the indicies are the following:
[5,7,9,...] you know edgeWeights[5] is the smallest, edgeWeights[7] is the second smallest, ...etc.


One obvious improvement would be to break the code up a bit more - identify standalone pieces of functionality and put them into functions, e.g.:

def read_data(filename):
    csvf = open(filename,'rU')
    rows = csv.reader(csvf)
    data = [row for row in rows]
    csvf.close()
    return data

offer_sheet = read_data('OfferInfo.csv')
transaction_sheet = read_data('Transactions.csv')

This reduces duplication and, therefore, possibilities for errors. It allows easier development, as you can create and test each function separately before connecting it all together. It also makes it easier to improve the functionality, in this case by adopting the with context manager:

def read_data(filename):
    with open(filename, 'rU') as csvf:
         return [row for row in csv.reader(csvf)]

You make that change in only one place and everywhere that calls it benefits.

I would also have as little code as possible at the top level. Instead, move it inside an enclosing function, and only call that function if we're running the file directly:

def analyse(offer_file, transaction_file):
    offer_sheet = read_data(offer_file)
    transaction_sheet = read_data(transaction_file)
    ...

if __name__ == "__main__":
    analyse('OfferInfo.csv', 'Transactions.csv')

This makes it easier to import the code you develop elsewhere without running the test/demo code.


Find maximum gap between elements of an array

The code looks pretty good. Here are a few suggestions to make it more Pythonic.

Use generator expressions to their fullest

The entirety of the initialization of a can be reduced from:

A = list(map(list, enumerate(A)))  # get list of [index,value]
for item in A:
    item[0], item[1] = item[1], item[0]  # swap index with value
a = sorted(A)  # sort list A as per values

for v, i in a:
    ....

To:

for v, i in sorted((v, i) for i, v in enumerate(A)):
    ....

Use Python's builtins:

Python has the max() function that will replace

gap_new = max_index - min_index  # find the maximum gap
if gap < gap_new:
    gap = gap_new

with:

gap = max(gap, max_index - min_index)

similarly:

if i > max_index:  # if current > max_index, set max to current
    max_index = i

can be just:

max_index = max(max_index, i)

pep8

The violations were very minor, by I recommend formatting your code in accordance
with pep8.  This is important
when sharing code, as the consistent style makes it much easier for other
programmers to read your code.  There are various tools available to
assist in making the code pep8 compliant.  I use the
PyCharm IDE which will show pep8
violations right in the editor.

Restructured Code:

def maximum_gap(A):
    """find maximum gap between index(j -i ) with  A[i] <= A[j]"""

    min_index = max_index = len(A)
    gap = 0

    for v, i in sorted((v, i) for i, v in enumerate(A)):
        if i < min_index:  # if current < min, set min & max to current
            min_index = max_index = i
        else:
            # if current > max, set max to current
            max_index = max(max_index, i)

        # find the maximum gap
        gap = max(gap, max_index - min_index)

    return gap

assert maximum_gap([-1, -1, 2]) == 2
assert maximum_gap([1, 3, 5, 7, 2, 4, 10]) == 6
assert maximum_gap([3, 2, 1]) == 0
assert maximum_gap([3, 2, 1, 4]) == 3
assert maximum_gap([2, 2, 1, 4, 3]) == 4
assert maximum_gap([0, 1, 2, 3]) == 3
assert maximum_gap([100, 100, 100, 100, 100]) == 4


Optimize Sieve of Eratosthenes for big numbers in Python

You can make this part a bit faster:
            for j in range(i*3, limitN, i*2):
                not_prime.add(j)

Better start at i*i, and better don't do your own loop. So it becomes:
            not_prime.update(range(i*i, limitN, i*2))


Parsing a list of single numbers and number ranges

Since the whole exercise is a string-transformation problem, I suggest performing it using a regex substitution.

import re

def expand_ranges(s):
    return re.sub(
        r'(\d+)-(\d+)',
        lambda match: ','.join(
            str(i) for i in range(
                int(match.group(1)),
                int(match.group(2)) + 1
            )
        ),
        s
    )

I think that expand_ranges would be a more descriptive name than unpackNums.


Importing text into PANDAS and counting certain words

Several errors:

  I then loop through each of these loops

I take it you mean "I then loop through each of these columns".

  for post in data['post]:

missing end quote mark

  scores = Func.countWords(posts)

You imported func (lowercase) and now you're calling Func (uppercase)

  data2 = data2.append(scores,ignore_index=True)

append should take a row-type object. If the function returns a numeric, then you shouldn't be appending it. Instead you can do:

def post_to_count(post):
      return func.countWord(str(post))

scores = data['post'].apply(post_to_count)


Golang execute several go routine in loop and then wait

Every time you execute a go statement it is passed to the scheduler. What if scheduling is delayed? wg.Add(1) is not executed and wg.Wait() is true. For example, run your code in the Go Playground where GOMAXPROCS is 1.

package main

import (
    "sync"
)

func main() {
    var wg sync.WaitGroup
    n := 5
    ch := make(chan int, n)
    for i := 0; i < n; i++ {
        println("Processing ", i)
        go process(i, ch)
        go consume(ch, &wg)
    }
    println("Finished the process")
    wg.Wait()
}

func consume(ch chan int, wg *sync.WaitGroup) {
    wg.Add(1)
    defer wg.Done()
    println("Result ", <-ch)
}

func process(i int, ch chan int) {
    ch <- (i * 5)
}

Playground: https://play.golang.org/p/dQ_lFRz2Y8a

Output:

Processing  0
Processing  1
Processing  2
Processing  3
Processing  4
Finished the process

Make sure that all the wg.Adds are run before wg.Wait. Move the println("Finished the process") to the correct place after the wg.Wait. For example,

waiting.go:

package main

import (
    "runtime"
    "sync"
)

func main() {
    println("GOMAXPROCS", runtime.GOMAXPROCS(0))
    var wg sync.WaitGroup
    n := 5
    ch := make(chan int, n)
    for i := 0; i < n; i++ {
        println("Processing ", i)
        go process(i, ch)
        wg.Add(1)
        go consume(ch, &wg)
    }
    wg.Wait()
    println("Finished the process")
}

func consume(ch chan int, wg *sync.WaitGroup) {
    defer wg.Done()
    println("Result ", <-ch)
}

func process(i int, ch chan int) {
    ch <- (i * 5)
}

Playground: https://play.golang.org/p/3czBixAjxdT

Output:

GOMAXPROCS 1
Processing  0
Processing  1
Processing  2
Processing  3
Processing  4
Result  0
Result  5
Result  10
Result  15
Result  20
Finished the process

Run the Go data race detector to check for data races. It finds none.

$ go run -race waiting.go
GOMAXPROCS 4
Processing  0
Processing  1
Result  0
Processing  2
Result  5
Processing  3
Result  10
Processing  4
Result  15
Result  20
Finished the process
$


You're allocating a new result matrix every time, then almost always throwing it away.  Only allocate one if the passed in c matrix is null.

Since you're recursion comes at the end (tail recursion), this could be changed over from recursion to a loop.  If your matrix is too large, the recursion depth will be too deep and you'll run out of stack space.  This won't happen with a loop.


String constructible from short list of words? AtCoder ABC049C - Daydream

It seems to be fine. What are the failing cases' inputs? Following your link I only see 3 cases which should indeed work.

However, I see there's a limitation of time and memory usage at the beginning, and that S max length is 100000. Your code might for example exceed maximum recursion depth.
I think a simpler solution would be to use regex. For example (and I added a long sample):

import re
import random

regexPattern = "^(dream(er)?|eraser?)*$"
sampleList = [
    "erasedream",
    "dreameraser",
    "dreamerer"]

# just add a looooooong sample
longSample = ""
mandatoryWords = ["dream", "dreamer", "erase", "eraser"]
while True:
    addWord = mandatoryWords[random.randint(0, 3)]

    if len(longSample) + len(addWord) > 100000:
        break
    else:
        longSample += addWord

sampleList.append(longSample)

for sample in sampleList:
    match = re.fullmatch(regexPattern, sample)

    if match != None:
        print("YES")
    else:
        print("NO")

outputs

YES
YES
NO
YES


First, let us collect the code pieces which are repeated

Fields

private final TestHelpers helpers;
private WebDriver driver;

Constructor related

helpers = new TestHelpers();
driver = helpers.getWebDriver();

Now, let's start refactoring by extending LoadableComponent<T>

public abstract class ExtendedLoadableComponent<T> extends LoadableComponent<T> {

    protected final TestHelpers helpers
    protected WebDriver driver;

    public ExtendedLoadableComponent() throws Exception {
        helpers = new TestHelpers();
        driver = helpers.getWebDriver();
    }
}

which reduces the first class to

public class VariablesPage extends ExtendedLoadableComponent<VariablesPage> {

    @FindBy(xpath = "//a[@title=\"Define new variable\"]")
    private WebElement btnAddNewVariable;

    public VariablesPage() throws Exception {
        super();
        helpers.setHar(VariablesPage.class.getSimpleName());
        PageFactory.initElements(driver, this);
        isLoaded();
        helpers.getHar();
    }

    @Override
    protected void load() {}

    @Override
    protected void isLoaded() throws Error {
        helpers.waitUntil(btnAddNewVariable);
    }
}

But wait, we can do better! So, let us also call helpers.setHar(String) and thus we need to refactor the constructor of ExtendedLoadableComponent<T>

public abstract class ExtendedLoadableComponent<T> extends LoadableComponent<T> {

    protected final TestHelpers helpers
    protected WebDriver driver;

    public ExtendedLoadableComponent(Class<T> pageClassToProxy) throws Exception {
        helpers = new TestHelpers();
        driver = helpers.getWebDriver();
        helpers.setHar(pageClassToProxy.getSimpleName());
        PageFactory.initElements(driver, pageClassToProxy);
    }
}

which reduces the first class to

public class VariablesPage extends ExtendedLoadableComponent<VariablesPage> {

    @FindBy(xpath = "//a[@title=\"Define new variable\"]")
    private WebElement btnAddNewVariable;

    public VariablesPage() throws Exception {
        super(VariablesPage.class);
        isLoaded();
        helpers.getHar();
    }

    @Override
    protected void load() {}

    @Override
    protected void isLoaded() throws Error {
        helpers.waitUntil(btnAddNewVariable);
    }
}

Naming

I don't know if the TestHelpers class is your own. If yes, you should think about changing the names for setHar() and getHar() so Mr. Maintainer can evaluate what they do by looking at the names.


Using model relationships to find number of responses by a user, to posts of a certain topic type

Try something like this, it would work if the #tagged_with method returns an ActiveRecord::Relation object, I don't know if you need a :user_id in there, but your code didn't hint on any, so I did the same.

Response.joins(:micropost).merge(
  Micropost.tagged_with(interest, on: :tags)
).count


Python has a style guide, which lays out guidelines for (among other things) code formatting. Your current code is compliant with the style guide, except that the help parameter for --channel means the line is too long.

You can easily avoid this by simply breaking the string across multiple lines:

parser.add_argument('-c', '--channel',
                    default='all',
                    help='channel/s to hop (i.e. 3 or 3,6,9 or 3-14 or all or 0 '
                    'for current channel')

Alternatively, you can shorten the message slightly and use one of the other recommended indent styles, which uses less horizontal space:

parser.add_argument(
    '-c', '--channel',
    default='all',
    help="channel/s to hop (e.g. '3', '3,6,9', '3-14', 'all', '0' (current channel)")


All your logging function take a Date as the first argument, with a default
value of the current date. Unless there is a special reason why a caller
should pass a custom date, you can remove that argument and compute the
date inside the logging function:

public func qLogHighlight<T>(file: String = #file, function: String = #function,
                             line: Int = #line, _ object: T) {
    QLog.log(LogEntry(date: Date(), file: file, function: function, line: line,
                      logLevel: .highlight, text: "\(object)"))
}

or even give the LogEntry constructor a default value for the date
parameter, so that you can omit it here:

public func qLogHighlight<T>(file: String = #file, function: String = #function,
                             line: Int = #line, _ object: T) {
    QLog.log(LogEntry(file: file, function: function, line: line,
                      logLevel: .highlight, text: "\(object)"))
}

Note also that

function names should start with a lowercase letter (compare General Conventions in the Swift API Design Guidelines),
it suffices to pass .highlight to the QLog.log() call instead
of LogLevel.hightlight, the type is automatically inferred from the
context.

If you want five separate logging functions, one for each level, then
I do not see more room for shortening. An alternative would be to
define just one logging function which takes the log level as an
argument:

public func qLog<T>(level: LogLevel, file: String = #file, function: String = #function,
                    line: Int = #line, _ object: T) {
    QLog.log(LogEntry(date: Date(), file: file, function: function, line: line,
                      logLevel: level, text: "\(object)"))
}

This would remove to code duplication completely.

Some more thoughts:

Creating a date formatter is “expensive,” it is better to create it once
and reuse it (compare e.g. the “Re-Using Formatter Instances” section in NSFormatter on NSHipster.

This can be done with a static property (which is computed lazily and
only once):

public struct LogEntry {

    static var formatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss"
        return dateFormatter
    }()

    ...

}

Instead of bridging to NSString one can use

URL(fileURLWithPath: file).lastPathComponent

to get the last path component of a file path.

Apart from special cases (such as escaping closures), properties can
be accessed without using self:

var metaText: String {
    return "\(LogEntry.formatter.string(from: date)): \(URL(fileURLWithPath: file).lastPathComponent):\(line) \(function): "
}


I like your code, but I just have a couple of small points:

Be consistent with your spacing (around { and especially .).
I doubt that this will work on Windows, so I would check if the script is run on Windows, if it is, just print without color (or find a way to use color in Windows), and maybe trigger a warning.
I would rename printc, either to the shorter print (because it's easier to remember, and you don't really lose any meaning), to print_color (if you want to make it really really explicit that it is in color), or print_console (in case you also later implement something like print_web with CSS).
I would not just ignore it if a color is requested that does not exist, but handle it in some way (throw an exception, trigger a warning, etc). Otherwise users might wonder why ligth_gray or orange do not result in any color changes.


The following code is very inefficient:

    Double sum = 0.0;

    for (Number num : value){
        sum += num.doubleValue();
    }

It creates a Double object for 0.0, and then, since Double objects are immutable, for every num in the value list, it creates yet another Double object for the resulting partial sum.  If you replaced Double with double, then you won't be creating new objects for each iteration through the loop.

Since you are already using the stream API, why not use DoubleStream::sum to sum the values as a double?

    double sum = value.stream().mapToDouble(Number::doubleValue).sum();

Finally, you could use the Collectors.toMap() stream method to create the map.

public Map<String, Double> add(Map<String, List<? extends Number>> map) {
    return map.entrySet().stream()
          .collect(Collectors.toMap(Map.Entry::getKey,
                                    e -> e.getValue().stream()
                                              .mapToDouble(Number::doubleValue)
                                              .sum()));
}

Whether or not this last step is an "improvement" may be a matter of taste.

Note: the return type is no longer a HashMap; it just a Map.

The add() method doesn't depend on any members of Adder, so the method should be static.  Then you can get rid of the Adder adder = new Adder() object.

Using List.of(...) and Map.of(...) can simplify your test code:

public static void main(String[] args) {

    List<Integer> list1 = List.of(1, 2, 3);
    List<BigDecimal> list2 = List.of(new BigDecimal("9.87654321e300"),
                                     new BigDecimal("987654321"),
                                     new BigDecimal("987654321"));

    Map<String, List<? extends Number>> hashMap = Map.of("list1", list1,
                                                         "list2", list2);

    System.out.println(Adder.add(hashMap));
}


Keep related data together.

Does your application need a list of contacts? Keep each contact intact with the second approach. Merging data to create and pass a single contact takes work and is error-prone.
Does it need a list of contact IDs? Do the same or return just that list. With the latter approach you can easily produce a limited array. Going the other way is much harder (more code).
Does it need a list of contact names in a drop-down that loads the full contact for one ID? Use the latter since you get everything up-front.

The short answer is Keep related data together because it's generally easier to pull it apart than merge it back together.


Scala TryWith that closes resources automatically

There are a couple of places where you can improve.

First the pedantic stuff.

Closable should probably be Closeable
Cleaning up your imports can make it easier to get to the parts of your program that matter. In this case you can consolidate your imports to a much simpler version:

import scala.util.control.NonFatal
import scala.util.{Failure, Success, Try}

Make sure it compiles before posting. In this case, there was a missed rename, and it needed an additional import to compile without warnings (needed by the reflected call to #close on a structurally typed value).
Several of your pairs of curly braces are optional, and removing them makes it much easier to read.
Scala convention favors single character for type parameters. I'm not sure that I 100% agree with this particular convention for classes with type parameters, but for a single method it's best to stick to the convention.

Ok, now that's out of the way, to the good stuff :)

Use interfaces if they are already there

Scala's interoperability with Java is one of it's strengths, so re-inventing an interface isn't really needed. Additionally, using java.io.Closeable gets rid of the structural typing, which is a nifty feature, but it's better to avoid if it's not strictly needed. This simplifies things considerably, particularly the type signature.

FlatMap

Try is a Monad, which means a bunch of stuff to category theory buffs - which I don't particularly care about. What I do care about Monads is that they have two methods defined on them that can make life much easier. flatMap is the first, and you've basically defined the content of this method in your outermost pattern match.

Refactored Version 1

import java.io.Closeable
import scala.util.control.NonFatal
import scala.util.{Failure, Success, Try}

object TryWith {
  def apply [C <: Closeable, R](resGen: => C) (r: Closeable => R): Try[R] =
    Try(resGen).flatMap(closeable => {
      try {
        Success(r(closeable))
      }
      catch {
        case NonFatal(e) => Failure(e)
      }
      finally {
        try {
          closeable.close()
        }
        catch {
          case e: Exception =>
            System.err.println("Failed to close Resource:")
            e.printStackTrace()
        }
      }
    })
}

Principle of Least Surprise

So far we haven't changed how the method actually works. In the possibilities you mentioned for how to handle a failure to close you missed the most important option: mimic the behavior of the Java try-with-resources block.

This is important for two reasons: the first is that it's a pretty sane way of handling this case, the second is that it will be the behavior expected by anyone coming from a Java background. Acting in an intuitive manner is a very powerful thing.

Java handles failures to close in this manner:

If the block throws an exception, give priority to this exception. The exception thrown by #close is added as a suppressed exception, and the modified exception is thrown.
If the block did not throw an exception, allow the exception from close to propagate upward.

The basic premise is that exceptions are exceptional, so they should never be swallowed.

Refactored Version 2

import java.io.Closeable
import scala.util.control.NonFatal
import scala.util.{Failure, Try}

object TryWith {
  def apply[C <: Closeable, R](resource: => C)(f: C => R): Try[R] =
    Try(resource).flatMap(resourceInstance => {
      try {
        val returnValue = f(resourceInstance)
        Try(resourceInstance.close()).map(_ => returnValue)
      }
      catch {
        case NonFatal(exceptionInFunction) =>
          try {
            resourceInstance.close()
            Failure(exceptionInFunction)
          }
          catch {
            case NonFatal(exceptionInClose) =>
              exceptionInFunction.addSuppressed(exceptionInClose)
              Failure(exceptionInFunction)
          }
      }
    })
}

The Test Suite

import java.io.Closeable
import org.scalatest.{ Matchers, WordSpec }
import scala.util.{ Failure, Success }

class TryWithSpec extends WordSpec with Matchers {
  // Exceptions and errors here so we don't pay the stack trace creation cost multiple times
  val getResourceException = new RuntimeException
  val inFunctionException = new RuntimeException
  val inCloseException = new RuntimeException
  val getResourceError = new OutOfMemoryError
  val inFunctionError = new OutOfMemoryError
  val inCloseError = new OutOfMemoryError

  val goodResource = new Closeable {
    override def toString: String = "good resource"
    def close(): Unit = {}
  }

  "TryWith" should {
    "catch exceptions getting the resource" in {
      TryWith(throw getResourceException)(println) shouldBe Failure(getResourceException)
    }

    "catch exceptions in the function" in {
      TryWith(goodResource){
        _ => throw inFunctionException
      } shouldBe Failure(inFunctionException)
    }

    "catch exceptions while closing" in {
      TryWith(new Closeable {
        def close(): Unit = throw inCloseException
      })(_.toString) shouldBe Failure(inCloseException)
    }

    "note suppressed exceptions" in {
      val ex = new RuntimeException
      val result = TryWith(new Closeable {
        def close(): Unit = throw inCloseException
      })(_ => throw ex)

      result shouldBe Failure(ex)
      val Failure(returnedException) = result
      returnedException.getSuppressed shouldBe Array(inCloseException)
    }

    "propagate errors getting the resource" in {
      intercept[OutOfMemoryError] {
        TryWith(throw getResourceError)(println)
      } shouldBe getResourceError
    }

    "propagate errors in the function" in {
      intercept[OutOfMemoryError] {
        TryWith(goodResource){
          _ => throw inFunctionError
        }
      } shouldBe inFunctionError
    }

    "propagate errors while closing" in {
      intercept[OutOfMemoryError] {
        TryWith(new Closeable {
          def close(): Unit = throw inCloseError
        })(_.toString)
      } shouldBe inCloseError
    }

    "return the value from a successful run" in {
      TryWith(goodResource)(_.toString) shouldBe Success("good resource")
    }
  }
}


Defining database connection parameters

It is not recommended to hard-code your connection parameters within the script.

You could for example parse the database properties from an external Json source. There are other methods available in Groovy as well, such as reading properties from XML, or from a database.properties file, or from a *.groovy file, but I think Json might be the one you would feel most comfortable with.

def dbProperties = new JsonSlurper().parseFile(new File('db.json'))

Where db.json is something like this:

{
    "url": "jdbc:postgresql://localhost/GroovyTest",
    "user": "Phrancis",
    "password": "test",
    "driver": "org.postgresql.Driver"
}

And then instantiating the Sql object:

def sql = Sql.newInstance(dbProperties.url, dbProperties.user, dbProperties.password, dbProperties.driver)

Strings

""" are used for multi-line strings, for single-line strings it is overkill.

sql.execute """SET SEARCH_PATH TO groovy_test;"""

Can become:

sql.execute "SET SEARCH_PATH TO groovy_test;"

Additionally, " is used for GString, that will work just fine here but is not required, a normal String would be enough. So we can use ' insteand so that it becomes:

sql.execute 'SET SEARCH_PATH TO groovy_test;'

Here you have a multi-line GString, but as you're not using any GString-specific features (variable interpolation for example), you can replace the """ with '''

sql.execute """
        START TRANSACTION;

        DROP TABLE IF EXISTS test;
        (...)

Duplicated SQL query string

This code is essentially repeated twice:

sql.execute """
        START TRANSACTION;

        INSERT INTO test (string, number, decimal, datetime)

            VALUES (?, ?, ?, CAST(? AS TIMESTAMP));

        COMMIT;""", params1

The only difference is that the second time params1 is exchanged for params2.

There are three ways to fix this:

Extract the query string to a variable
Extract a method, which takes the params as input and performs the query
Extract a method closure. (Very similar to extracting a method)

First approach would look like this:

def query = """
        START TRANSACTION;

        INSERT INTO test (string, number, decimal, datetime)

            VALUES (?, ?, ?, CAST(? AS TIMESTAMP));

        COMMIT;"""

sql.execute query, params1
sql.execute query, params2

Second approach:

void sqlInsert(List<Object> params) {
    sql.execute """
        START TRANSACTION;

        INSERT INTO test (string, number, decimal, datetime)

            VALUES (?, ?, ?, CAST(? AS TIMESTAMP));

        COMMIT;""", params
}

sqlInsert query, params1
sqlInsert query, params2

Note that sqlInsert query, params1 is the same as sqlInsert(query, params1)

Third approach:

def sqlInsert = { List<Object> params ->
    sql.execute """
        START TRANSACTION;

        INSERT INTO test (string, number, decimal, datetime)

            VALUES (?, ?, ?, CAST(? AS TIMESTAMP));

        COMMIT;""", params
}

sqlInsert.call(params1)
sqlInsert.call(params2)

// or alternatively
sqlInsert(params1)
sqlInsert(params2)


Writing/reading data structure to a file using C++

The trouble with writing binary blobs is that they lead to brittle storage.

The stored objects have a tendency to break over time as the assumptions you make about the hardware no longer hold true (in this case that the sizeof(int) is constant and the endianess of int will not change).

It has become more standard therefore to use a method know as serialization. In this you convert the object to a format that is hardware agnostic (and usually human readable).

Note: Binary blobs have advantages. But you must weigh those against the brittleness. Therefore your first choice should be serialization (unless you have specific requirements that prevents this). Then look at binary Blobs only after you have shown that serialization has too much overhead (unlikely for most situations, but it is a possibility).

In C++ you would do this using the operator<< and operator>>.

I would re-write your code as:

struct WebSites
{
    std::string siteName;
    int rank;

    WebSite()
        : siteName("")
        , rank(0)
    {}

    WebSite(std::string const& siteName, int rank)
        : siteName(siteName)
        , rank(rank)
    {}
    void swap(WebSites& other) throws()
    {
        std::swap(rank,     other.rank);
        std::swap(siteName, other.siteName);
    }
};
std::ostream& operator<<(std::ostream& stream, WebSites const& data)
{
    stream << data.rank << " "
           << data.siteName.size() << ":"
           << data.siteName;
    return stream;
}
std::istream& operator>>(std::istream& stream, WebSites& data)
{
    WebSite     tmp;
    std::size_t size;
    if (stream >> tmp.rank >> size)
    {
        tmp.siteName.resize(size);
        if (stream.read(tmp.siteName[0], size)
        {
            data.swap(tmp);
        }
    }
    return stream;
}

Now you can write your code like this:

int _tmain(int argc, _TCHAR* argv[])
{
    WebSite s1("www.ppp.com", 0);
    WebSite s2("www.rrr.com", 111);
    WebSite s3("www.code.com", 123);
    WebSite s4("www.yahoo.com", 14);

    // write
    fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app);
    binary_file << s1 << s2 << s3 << s4;
    binary_file.close();

    // Read data
    fstream binary_file2("c:\\test.dat",ios::binary|ios::in| ios::ate );
    WebSites p_Data;
    while(binary_file2 >> p_Data)
    {
        cout << p_Data.SiteName << endl;
        cout << "Rank: "<< p_Data.Rank << endl;
    }
    binary_file2.close();

    // Read data into a vector
    fstream binary_file3("c:\\test.dat",ios::binary|ios::in| ios::ate );
    std::vector<WebSites> v;

    std::copy(std::istream_iterator<WebSites>(binary_file3),
              std::istream_iterator<WebSites>(),
              std::back_inserter(v)
             );
    binary_file3.close();
}


Picasso's Transformation class to Crop borders from Image

To be fair, I think it is quite readable  and I do not know of a way to really improve it using Java 8 constructs. I have a tip or two anyway:

In the getXNonWhitePosition methods, I'd remove the internal check to assign the first value, assigning it before the loop:

private int getFirstNonWhitePosition(int[] horizontalMiddleArray) {
    if(horizontalMiddleArray.length == 0) {
        return -1;
    }
    int left = horizontalMiddleArray[0];
    for (int i = 1; i < horizontalMiddleArray.length; i++) {
        if (left != horizontalMiddleArray[i]) {
            return i;
        }
    }
    return -1;
}

You could implement the isNegative with a Java 8 stream, e.g.:

private boolean isNegative(final int... values) {
    return IntStream.of(values).allMatch(value -> value > 0);
}

Why do you save mWidth and mHeight in the fields? Because it seems to me like the transformation has nothing to do with it. These values will change after each transformation application. Using them for the toString feels quite odd.

If I would really want to use Java 8 for the getXNonWhitePosition methods, I think something like the following would do:

private int getFirstNonWhitePosition(final int[] horizontalMiddleArray) {
    if(horizontalMiddleArray.length == 0) {
        return -1;
    }
    final int left = horizontalMiddleArray[0];
    return IntStream.range(1, horizontalMiddleArray.length)
            .filter(index -> horizontalMiddleArray[index] != left)
            .findFirst()
            .orElse(-1);
}

private int getLastNonWhitePosition(final int[] horizontalMiddleArray) {
    if(horizontalMiddleArray.length == 0) {
        return -1;
    }
    final int right = horizontalMiddleArray[horizontalMiddleArray.length - 1];
    return IntStream.rangeClosed(2, horizontalMiddleArray.length)
            .map(index -> horizontalMiddleArray.length - index)
            .filter(index -> horizontalMiddleArray[index] != right)
            .findFirst()
            .orElse(-1);
}

This is not tested, though I think it works. But again, I do not think this is much of an improvement. You could technically extract to a function which receives some value to check against, and some kind of indexing stream, but that feels like over engineering to me.


Find the center of n squares which together build a rectangle

A couple of notes:

The width, height and number of sub-rectangles should be parameters, not local variables. If you should, for example, want to print out the centres for differing values of w, h and n, calling the method in a loop with different arguments is more convenient than changing the code and rerunning it multiple times.
Determining the size of the sub-rectangles and collecting their centres could be done in two separate methods because a) they can easily be separated as they're not intertwined b) it makes it immediately obvious which part is done by which code and c) they might be useful on their own.
Rather than outputting the centres, you should return them in an array or list. This way you can also easily use the method in a context where you don't want to print the centres or want to do something to them before printing. Also it's generally a good practice to separate IO code from logic code.
Since both i and j are ints and thus minDistance will only ever hold integer values, it should have type int, not double. Otherwise it leaves the impression that it could possibly have a non-integer value.
On a similar note you should probably make the type of width and height int as well since the first thing you do is to truncate them to ints. Having their type be double might make the user of your method think the results will be more accurate than they really are.


Can this code be optimized in any way?

Some of the obvious points:

Remove unnecessary #include statements

Your code doesn't use any stuff from these headers

#include <cmath>
#include <cstdio>
#include <vector>
#include <algorithm>

So you can remove them.

Don't use using namespace std;

That's generally considered bad practice.

Rather use

using std::cout;
using std::cin;

if you want to avoid typing these out.

Use meaningful variable names

Variable names like

int n,q;
int A[n];

don't tell anything about their semantics.

Standard C++ doesn't support VLA's

Code like

int A[n];

isn't portable. Variable Length Arrays aren't supported by the current c++ standard.

Use

std::vector A(n);

instead to create a dynamically sized array.

Check for successful and valid input

cin>>a>>b>>x>>y;

You never check if the above statement succeeded before proceeding to apply the algorithm.

Better do something like

if(!(cin>>a>>b>>x>>y)) {
    std::cout << "Bad input encountered!" << std::endl;
    return 1;
}

Since

t%x

may segfault when x is zero, you should at east have an assert:

std::assert(x);
if(t%x==y) { // ...
}

Always use braces for scoped blocks

for(int i=0;i<n;i++)
    cin>>A[i];

should be

for(int i=0;i<n;i++) { // <<<<<<<
    cin>>A[i];
} // <<<<<<<<

Missing the braces makes that code error prone for changes. It's always better to  clarify the scope with conditional or loop statements.

Use prefix incrment (decrement) if you don't need to preserve the previous value

Instead of

for(int i=a;i<=b;i++)
c++;

use

for(int i=a;i<=b;++i)
++c;

You obviously don't need the old value preserved by the postfix increment operations.

Performance of formatted text extraction

  The values of of n,q,a,x,y,b are ranging from 1 to 40000. so it gets the timeout therefore it needs to further optimised

As for your performance concerns:

Formatted text extraction in c++ is costly. You may get a performance improvement just using scanf() in this case.

While

cin>>a>>b>>x>>y;

applies four function calls

scanf("%d %d %d %d",a,b,x,y);

would be only one call. Also the internal implementation of the formatted text extraction syntax boils down to some scanf() like functions for most of the c++ compilers anyways.


The string "id" is used three times in TestSlideView(): make it a const string instead.

Same for "Slide", as used in TestSlideView() and Slide(string slideid).

Don't name something SlideList, name it Slides. And yes, I know you named it SlideList because you already have a property called Slides, but Slides isn't an appropriate name for a single SlideModel anyway.

Even worse: listOfSlides.

Your variable names don't tell me what they contain: cs, stm, etc. I can figure out that "cs" means "connectionString", but I shouldn't be wasting effort on such things.

Also, why bother assigning dbPath to cs? Why not simply use dbPath (and perhaps rename that to connectionString)?

Same for assigning id to slideid -- which should be named slideId since it is a compound word. Matter of fact, why isn't the parameter named slideId in the first place?

"Danger, Will Robinson!" You code is now vulnerable to SQL injection:

"SELECT * FROM Slide WHERE ID = " + slideid;

Use the Parameters collection instead.

Also: looping through a SQLiteDataReader seems quaint to me. Why not store the result in a DataTable and work with that? Or even better: why not work with an ORM like NHibernate or Entity Framework?


In whole not bad, but something can be simplified.

1.
In short functions don't need to create separate variables, especially if it is just a wrapper over the call of inner function. So play game/1 from rps can be rewritten as:

play_game(InputFunctions) ->
  play_game([{win, 0}, {loss, 0}, {tie, 0}], InputFunctions).

2.
Behavior of function for get result from player2 must not depend on result first player. Together with hint from 1 and giving an alias to the name of argument get

play_game(Score, {Player1Input, Player2Input} = P) ->
  display_score(Score),
  case Player1Input() of
    quit -> ok;
    Input -> play_game(new_score(Input, Player2Input(), Score), P)
  end.

where Player2Input/0:

  GetCompInput = fun() ->
    Input = rps:get_random_symbol(),
    io:format("Computer threw ~p~n", [Input]),
    Input
                 end,

new_score in my opinion, better captures the essence of the function than compare_results. This also allow delete first clause in new_score(compare_results)/3.

3.
Usage the symbol - in the name of the module is not very convenient,
 because you must wrap the name in ' ' when call function. Better use _ as delimiter.

4.
Not should use guard,when can use pattern matching. Compare

fun(Continue) when Continue =:= false ->

and

fun(false) ->

5.
Do not create an anonymous argument for a single function clause, in this case it is just an excess parameter.

 main(_) ->

6.
Do not use the directive import since it can will only confuse. If you know
C++, it is possible to draw an analogy with an indicate explicit namespace instead of using namespace.

In addition I did not delete lines

play_game(ok, _) ->
  ok;

and

new_score(_, quit, _) ->
  ok;

although when playing with the computer this function clause does not get called.


Review

Private Sub CopyPaste(rngSrc As Range, rngDest As Range)

Prefixing variables with their type is a bit dated.   Of course there are times when it is invaluable such as working with forms where their is a designer and a code module.  Using simple meaningful names will make you code easier to read.

Private Sub CopyPaste(Source As Range, Destination As Range)

There is no need to name temporary objects.

ActiveWorkbook.Sheets.Add.Name = "_wsDummy_Temp_"
Dim wsDummy As Worksheet
Set wsDummy = ActiveWorkbook.Sheets("_wsDummy_Temp_")

It better to set your variables directly whenever possible.

Set wsDummy = ActiveWorkbook.Sheets.Add

Since the worksheet is just temporary and the code is short, I would use a With block and eliminate the wsDummy variable altogether.

With ActiveWorkbook.Sheets.Add
    .Paste Link:=True
    <more code>
End With

Worksheets are activated with Range("A1") selected whenever they are added.  So eliminate these lines:

wsDummy.Activate
wsDummy.Range("A1").Select

Ay-ay-ay rngSrcSrcRng!!  This variable is just an alias for rngDummy`.   Pick a name and stick with it.   I take this concept to the extreme.  You will see the same names throughout all my code projects.
IMO, consistently using simple names like data ( array ), results ( array ), result (scalar value), r (row index) , c (column index), n (generic index), text ( simple string ), contents ( simple string usually file contents), source (source object such as a range) , destination (destination object such as a range), cell, target don't just make it easier to read and modify your code but it also makes it far quicker to write the code, in the first place.
vTransposed isn't needed either.  It would be better to reuse vSrcSrc then to keep both variables in memory.
Clearing the contents of a temporary worksheet.  I'm guessing this is a remnant of code from your earlier attempts.

rngDummy.ClearContents

After your macros complete Application.DisplayAlerts and Application.ScreenUpdating are automatically reset.  So these lines can be removed:

Application.DisplayAlerts = True
Application.ScreenUpdating = True

It is best to set Application.Calculation = xlCalculationManual when changing values or formulas on a worksheet.
Refactored Code
Private Sub CopyPaste(Source As Range, Destination As Range)
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim calculationMode As XlCalculation
    calculationMode = Application.Calculation

    Dim results As Variant

    Source.Copy
    With Worksheets.Add
        .Paste Link:=True
         With .Range("A1").CurrentRegion
            results = Application.ConvertFormula(.Formula, xlA1, xlA1, 1)
            Destination.Resize(.Columns.Count, .Rows.Count) = Application.Transpose(results)
        End With
        .Delete
    End With

    Application.Calculation = calculationMode
End Sub

Alternate Approach
A more efficient method create the formula array using Range.Address(RowAbsolute:=True, ColumnAbsolute:=True, External:=True).  This will eliminate the need for a temporary worksheet and avoid the copy and pasting.
 Private Sub TransposeLink(Source As Range, Destination As Range)
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim calculationMode As XlCalculation
    calculationMode = Application.Calculation

    Dim results As Variant
    With Source
        ReDim results(1 To .Columns.Count, 1 To .Rows.Count)

        Dim r As Long, c As Long

        For r = 1 To .Rows.Count
            For c = 1 To .Columns.Count
                    results(c, r) = "=" & .Cells(r, c).Address(RowAbsolute:=True, ColumnAbsolute:=True, External:=True)
            Next
        Next

        Destination.Resize(.Columns.Count, .Rows.Count).Formula = results
    End With

    Application.Calculation = calculationMode
End Sub


Accelerate set of sed commands in files (recursively over full directory)

There's a gross inefficiency in this script: not only are we opening each file n times (where n is the number of lines), we're also running n find instances.

Instead, consider running find just once, and using a single sed command to perform the substitutions.  The easiest way to do that is to make it an executable script (with a #! line):

#!/bin/sed -f

s% '/mywar/% '/clientwar/%g
s%,'/mywar/%,'/clientwar/%g
s% "/mywar/% "/clientwar/%g
s% file="/mywar/% file="/clientwar/%g
s%<TAB>href="/mywar/%<TAB>href="/clientwar/%g
s% href="/mywar/% href="/clientwar/%g
s% name="/mywar/% name="/clientwar/%g
s% relativePath="/mywar/% relativePath="/clientwar/%g
s% requestUrl.indexOf("/mywar/")% requestUrl.indexOf("/clientwar/")%g
s% src='/mywar/% src='/clientwar/%g
s%<TAB>src="/mywar/%<TAB>src="/clientwar/%g
s% src="/mywar/% src="/clientwar/%g
s% url('/mywar/% url('/clientwar/%g
s% url("/mywar/% url("/clientwar/%g
s% url(/mywar/% url(/clientwar/%g
s% url="/mywar/% url="/clientwar/%g
s% value="/mywar/% value="/clientwar/%g
s% webapps/mywar/core% webapps/clientwar/core%g
s% window.open("/mywar/"% window.open("/clientwar/"%g
s%Disallow: /mywar/%Disallow: /clientwar/%g
s%http://localhost:8080/mywar/%http://localhost:8080/clientwar/%g
s%http://localhost:9200/mywar/%http://localhost:9200/clientwar/%g

We can now run that for every file:

find . -type f -exec scriptname.sed -i {} +

Or (with GNU Find and Parallel), we can use as many processor cores as we have available:

find . -type f -print0 | parallel -0 -X scriptname.sed -i

We can combine some of the search patterns.  For example, consider these three substitutions:

s% '/mywar/% '/clientwar/%g
s%,'/mywar/%,'/clientwar/%g
s% "/mywar/% "/clientwar/%g

They can be replaced with a single substitution, using \1 to retain the part we want to keep unchanged:

s%\([ ,]'\| "\)/mywar/%\1/clientwar/%g

This can be extended to almost all the substitutions (excepting only the ones that need to match text beyond the end of mywar/).

If all those backslashes are irritating, consider using (GNU) grep's -r option to enable extended regular expressions (but then you'll need to escape the literal ( that are to be matched, so it might not be worth it).


Lookup map for converting Strings into Android `R.raw` integers

There is not such thing as ArrayMap in standard Java. Therefore, I am just going to assume that you meant HashMap.

I would choose neither of those options. Depending on how many elements you need to insert into that Map, you could end up with a big chunk of code that is just a group of add calls.

I recommend creating two arrays: one of the Strings, and one of the Integers.

Then, all you have to do is create a loop that inserts all the values into the map.

Here is what I came up with:

String[] foos = {...};
Integer[] bars = {...};
Map<String, Integer> map = new HashMap<String, Integer>();

for(int i = 0, length = foo.length; i < length; i++) {
    map.put(foos[i], bars[i]);
}


I want to verify if argument value passed to a function is an instance of X

You have a subtle bug in your line if value and isinstance(value, correct_instance) is False:

First, you should not identity compare to False, just use if value and not isinstance(value, correct_instance):.

Now, what if value is a falsey value, for example consider trying to do obj = Object(); obj.y = "". This will not raise a TypeError, because "" is not a truthy value, so it will never get to the isinstance because of short-circuiting.

I'm not sure why you have it in there in the first place. Were you trying to protect against None values? If that is the case, use if value is not None. Here you want identity comparison (and not equality/truthiness).

As Peilonrayz said in the comments, this is mentioned at the end of PEP8, Python's official style-guide. It is worth a read and actually quite readable.

What is nice about your code is that it allows allowing multiple classes. isinstance takes a tuple of classes to check or a single class.
So you could use {'x': str, 'y': (int, float)} and it should still work.


Python3 Stack implementation with List built-in - Round Two

If you don't care if the error is textually correct, then you can remove the if in pop and peek.
You don't need to find the length of the stack to find the last element. You can just use self._stack[-1].

Creating:

class Stack:
    def __init__(self):
        self._stack = []

    def __len__(self):
        return len(self._stack)

    def pop(self):
        return self._stack.pop()

    def peek(self):
        return self._stack[-1]

    def push(self, item):
        self._stack.append(item)

    def __iter__(self):
        return iter(self._stack)

From this, it begs the question why not inherit from list? Which would make the code:

class Stack(list):
    def peek(self):
        return self[-1]

    def push(self, item):
        self.append(item)

If you're likely to switch to another form of Stack, then you may want to keep with this. However, for the most part I'd recommend not using this class. As the only benefit it has over list is that it's likely to work with more Stack interfaces.