Convert a List of graph edges to a Map of neighboring nodes

It is possible to achieve the same result with a scala.collection.immutable.Map:

def create_graph2(edges: Array[Array[Int]]): Map[Int, List[Int]]  = {
       // group the tuples so that a -> Array((a, b1), (a, b2), (a, b3)...)
  edges.groupBy(edge => edge(0))
       // convert the array to target list of Ints, removing duplicates
       .map{ case(key, edges) => (key, edges.map(_(1)).toSet.toList)}
}

Using the following test case:

val test1 = Array(Array(1, 2), Array(2, 3), Array(3, 4), Array(1, 5))
val result1 = create_graph(test1)
val result2 = create_graph2(test1)

The results are:

result1 = Map(2 -> List(3), 1 -> List(5, 2), 3 -> List(4))
result2 = Map(2 -> List(3), 1 -> List(2, 5), 3 -> List(4))


Interview task to efficiently find compact representation of nodes in tree and find big O time

This is, strictly speaking, off-topic for Code Review, because it's a question of algorithm design, not one of implementation. But I'll try to explain how I would approach it.

1. Notation

In order to describe an algorithm and its performance, we need some notation. So:

\$n\$ is the number of nodes in the tree;
\$M\$ is the set of nodes we want to compact;
\$m = |M|\$, the initial number of nodes in \$M\$;
\$C(x)\$ is the set of children of the node \$x\$ in the tree.
\$P(x)\$ is the parent of the node \$x\$ in the tree.

I'm going to assume that I can test for membership in a set in amortized time \$O(1)\$ and add or remove an element from a set in amortized time \$O(1)\$. This means we need to use Python's set data structure.

2. Eliminate redundancies

The set \$M\$ might be redundant: namely it might contain nodes \$x\$ and \$y\$ such that \$y\$ is an ancestor of \$x\$ (that is, \$y = P(x)\$ or \$y = P(P(x))\$ or ...). All such \$x\$ need to be removed from \$M\$. For example, the set \$\{B, C, D, J\}\$ is redundant because \$B = P(P(J))\$ and so \$J\$ can be removed.

This can be done in one depth-first traversal over the tree:

Initialize \$k\$ to 0.
On entering a node \$x ∈ M\$: if \$k = 0\$, set \$k = 1\$, otherwise remove \$x\$ from \$M\$.
On leaving a node \$x ∈ M\$: set \$k = 0\$.

This visits each node once and so takes time \$O(n)\$.

3. The naïve algorithm

Any algorithm for this problem is going to have to find nodes all of whose children are in the set of nodes to be compacted (that is, to find nodes \$x\$ where \$C(x) ⊆ M\$), and update the set of nodes accordingly.

So the first algorithm that springs to mind is the simple one in which we repeatedly search the whole tree for a node \$x\$ matching that condition, stopping when we can't find any more such nodes. Formally:

Eliminate redundancies from \$M\$ as described above.
For each non-leaf node \$x\$ in the tree:
  If \$C(x) ⊆ M\$ then:
    Update \$M\$ to \$(M \setminus C(x)) ∪ \{x\}\$
    Go to step 2.

What's the complexity of this algorithm? Step 1 takes time \$O(n)\$. Step 3 takes \$O(m)\$ (since \$M\$ stays the same or gets smaller as the algorithm progresses) and so does step 4 (for the same reason), so each loop 2–5 over the nodes in the tree takes time \$O(mn)\$, and we run that loop \$O(n)\$ times. The overall complexity is thus \$O(mn^2)\$.

4. Looking at the nodes in the right order

How can we improve this algorithm? It would be nice not to have to restart the loop over the nodes in the tree each time we update \$M\$. The reason we restart the loop is because updating \$M\$ might make a compaction available that we already considered and rejected. So we have to start over from the beginning so that we don't miss any compactions.

But if we looked at the nodes in the right order: that is, if we always looked at the children of \$x\$ before looking at \$x\$, then this couldn't happen. This order of traversing a tree is known as post-order.

So the revised algorithm looks like this:

Eliminate redundancies from \$M\$.
For each non-leaf node \$x\$ in post-order:
  If \$C(x) ⊆ M\$ then:
    Update \$M\$ to \$(M \setminus C(x)) ∪ \{x\}\$

Here the loop 2–4 takes \$O(mn)\$ as before, but we only execute it once, for an overall complexity of \$O(mn)\$.

5. Speeding up the subset test

The step that is contributing the most to the overall complexity is the subset test \$C(x) ⊆ M\$, which is executed \$O(n)\$ times and costs \$O(m)\$. How could we speed this up? The insight here is that all we need to know is the number of items in \$C(x) ∩ M\$, because when \$|C(x) ∩ M| = |C(x)|\$ then \$C(x) ⊆ M\$. So we can maintain a count for each node, of the number of its children that are in \$M\$, and just compare the counts. This results in the following algorithm:

Eliminate redundancies from \$M\$.
Initialize a map \$K\$ from nodes to non-negative integers such that \$K(x) = |C(x) ∩ M|\$, the number of children of \$x\$ that are in the set of nodes to be compacted.
For each non-leaf node \$x\$ in post-order:
  If \$K(x) = |C(x)|\$ then:
    Update \$M\$ to \$(M \setminus C(x)) ∪ \{x\}\$
    Update \$K(P(x))\$ to \$K(P(x)) + 1\$

Here step 1 takes \$O(n)\$, step 2 takes \$O(m)\$, the loop 3–6 is executed \$O(n)\$ times, steps 4 and 6 take \$O(1)\$ each time they are executed, so \$O(n)\$ overall, and step 5 takes \$O(n)\$ overall since each node can be removed from \$M\$ at most once and added to \$M\$ at most once. So the overall complexity is \$O(n)\$.


Avoid while(true) in task scheduling code

The question is a bit diffuse but I can give some hopefully useful feedback to help you move forward.

First of all I have to say that there are many libraries available for scheduling tasks. So be aware that you are reinventing the wheel, not to mention a very non-trivial wheel!

Threading is difficult, I recommend you have a look at http://www.albahari.com/threading/

Using while(true) is fine. But you should pause execution within the loop to avoid spinning cpu. One way would be to figure out when the next task is scheduled to run and Thread.Sleep until then. You also need to deal with the situation where a new task is added that is due before the call to Sleep returns.

Consider using a callback to deal with completed tasks and update the Log/Status.

The Tasks field is public so TaskManager is not thread safe. Consider making it private and adding synchronized methods to manipulate it. Also, the DataPumpTask objects used as keys are mutable. What happens if the client code reads/writes these objects while they are being manipulated by the TaskManager thread?

I wouldn't use a for loop to iterate a dictionary unless I needed the loop index variable for some reason. Try this instead:

foreach(KeyValuePair<DataPumpTask, Task> pair in Tasks)
{
    var dataPumpTask = pair.Key;
    var task = pair.Value;
    //do stuff
}


Length of the longest sequence of repeating characters

The missed edge case

The test case you're missing is longer text with non-repeating letters, for example: abcdefghijkl. And it's easy to fix that: just add these lines before the return statement:

    if (holder > charBlock) {
        charBlock = holder;
    }

The biggest clue for figuring out this problem was around these lines:

if((str.length() == 2) && (str.charAt(i) != str.charAt(i+1))){
    charBlock =1; //return 1 if the length of the string is 2 and non of the two chars match
}
else if((str.length() == 3) && (str.charAt(i) != str.charAt(i+1))){
    charBlock = 1; //return 1 if the length of the string is 3 and non of the three chars match
}
else if (str.charAt(i) == str.charAt(i+1)){

That is, the special treatment for length 2 and 3. There doesn't seem to be a logical reason to treat these cases any special, and you could have quessed that this might break for longer strings. And as it turns out, these conditions are completely unnecessary: you can safely remove them, and the code will still pass the tests.

Code review

About this piece:

  int charBlock = 0;
  int holder = 1;
  if(str.length() == 0){ //If string is empty return 0
     charBlock = 0;
  } else if(str.length() == 1){ //If string contains only a single char return 1
     charBlock = 1;
  } else {
     // ...
  }
  return charBlock;

Two things:

It's good to use early returns to reduce the indent level and make the code more readable
It's good to limit variables to the smallest scope possible

These two ideas go hand in hand in this example. Consider this alternative:

    if (str.length() == 0) {
        return 0;
    }
    if (str.length() == 1) {
        return 1;
    }
    int charBlock = 0;
    int holder = 1;
    // ...
    return charBlock;

The guard statements don't need the charBlock or holder variable,
they can simply return,
and now those variables are declared where they are really needed.

When checking if a string is empty, use str.isEmpty() instead of checking on the length.

And in this program, you don't actually need the str.length() == 1 check,
if you omit it the program will still work and pass the tests.

But the single biggest problem with this code, in my opinion,
is the naming of the variables charBlock and holder.
I would name them longest and length, respectively.

Putting the above suggestions together, the implementation becomes this:

    if (str.isEmpty()) {
        return 0;
    }
    int longest = 0;
    int length = 1;
    for (int i = 0; i < str.length() - 1; i++) {
        if (str.charAt(i) == str.charAt(i + 1)) {
            ++length;
            if (length > longest) {
                longest = length;
            }
        } else {
            length = 1;
        }
    }
    if (length > longest) {
        longest = length;
    }
    return longest;

Almost. There is one more important improvement to do: why update the longest length while still counting the same letters? It would be more efficient to move that piece of code to the else block, like this:

        if (str.charAt(i) == str.charAt(i + 1)) {
            ++length;
        } else {
            if (length > longest) {
                longest = length;
            }
            length = 1;
        }

Unit testing

When refactoring non-trivial code like this,
it's good to have unit tests to make it easy to re-validate everything, for example:

@Test
public void test_hoopla() {
    assertEquals(2, maxBlock("hoopla"));
}

@Test
public void test_abbCCCddBBBxx() {
    assertEquals(3, maxBlock("abbCCCddBBBxx"));
}

@Test
public void test_empty() {
    assertEquals(0, maxBlock(""));
}

@Test
public void test_xyz() {
    assertEquals(1, maxBlock("xyz"));
}

@Test
public void test_xxyz() {
    assertEquals(2, maxBlock("xxyz"));
}

@Test
public void test_longer_nonrepeating_sequence() {
    assertEquals(1, maxBlock("abcdefghijkl"));
}

Especially when the contest provides the cases you should pass.
Heck, it's good to write unit tests always.


Critique & improve a file reading routine

At first glance, you're looking for loops collect clause.

(defun read-sim-file (filename)
  (let ((file-text-list (split "\\n" (batteries:read-text-file filename))))
    (loop for line in file-text-list
      when (scan "TRAP ET" line)
        do (error "Trap ET detected o_o")
      unless (scan "DBG_INT" line)
        collect line)))

At second glance, you can do this much more efficiently using with-open-file instead of breaking your input file up into a list (this should save you two traversals of said file)

(defun read-sim-file (filename)
  (with-open-file (stream filename)
    (loop for line = (read-line stream nil 'eof) until (eq line 'eof)
      when (scan "TRAP ET" line)
        do (error "Trap ET detected ಠ_ಠ")
      unless (scan "DBG_INT" line)
        collect line)))

The first one is a fairly basic loop directive, the second one is almost verbatum an example out of the CL Cookbook "files" section (the whole cookbook contains many other useful recipes too).

Just as a sidenote, do try to indent things properly. It was more difficult than it should have been to read your initial program. If you ever catch yourself leaving comments like ;; intentional newline, think hard about what you just wrote.

Now that I've had some proper sleep, lets take the new one apart for educational purposes.

  (with-open-file (stream filename)

This line opens up a file and creates a handle for it named stream. Nothing has actually been read yet, you've just got a stream to pull from.

    (loop for line = (read-line stream nil 'eof) until (eq line 'eof)

loop has a couple of non-obvious directives. This is one of them (and coincidentally, the reason that some lispers prefer the non-standard iterate module; there's a feeling that infix notation isn't Lispy enough. I disagree, just like to point it out).

read-line takes a stream and a few options and returns the first line from that stream. (read-line stream nil 'eof) means "Read the next line from stream, don't error at the end of file marker (that's the nil) and return the symbol eof when you reach the end of the file.

The full line then reads "Loop through the lines in stream until you hit 'eof".

      when (scan "TRAP ET" line)
        do (error "Trap ET detected ಠ_ಠ")

loop has conditional directives too, so you don't need to resort to cond here. if, else, when and unless are all valid forms.

      unless (scan "DBG_INT" line)

Speaking of unless, you can use it to skip "DBG_INT" lines without devoting a separate clause to them.

        collect line))

This does the same thing as

     (setf tmp (append return_list (list line)))

which is to say, it creates a list where the elements are collected in order they're encountered (though there isn't an actual named variable that). The loop form also returns whatever you've collected if that's the last clause in the statement (so you don't need to explicitly return it).


Application for allowing a user to "follow" another user

This is how I'd do it. There may be flaws because you haven't provided your HTML.

I assume that within the click handler, you only want to interact with the current element being clicked. The reason I say that is because you had $('.follow') a number of times in there, which would affect all .follow elements.

         //     v--- makes the shortcut available inside the .ready() callback
jQuery(function($) {
    $('.follow').click(function(event) {
        event.preventDefault();

            // assuming it's a link, no need for jQuery here
        var url = this.href;

            // Looking at the code in your callback, I assume you only have text content
        var followtype = this.innerHTML;

            // I assume you actually want just the current "follow", not all
        var user = url.match('/relationships/[a-z]+/([a-z]+)/following/');

            // Make certain there was a match before accessing the Array.
            // If there was no match, just return the function
        if( user )
            user = user[1];
        else
            return;

        var postdata = {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        };
            // Inside the $.post callback, are we still only working with the current
            //   "follow" clicked? If so, cache it here, and use it in the callback
        var this_follow = this;

        $.post(url, postdata, function(json){
            if(json.result == '1') {
                if(followtype == 'Follow') {
                     this_follow.innerHTML = 'Unfollow';
                     this_follow.pathname = '/relationships/remove/'+user+'/following/';
                } else {
                    this_follow.innerHTML = 'Follow';
                    this_follow.pathname = '/relationships/add/'+user+'/following/';
                }
            }
        })
    });
});

As you can see, I tend to eliminate jQuery when convenient.

I should note that using .innerHTML in the way I have is cheating a bit. It's an HTML parser really, but it's convenient for changing small chunks of text quickly.

To do it properly, you'd select the child text node of the element, and change its nodeValue.

this_follow.firstChild.nodeValue = 'Unfollow';


Note: although I hinted in a comment that there's a O(n * K) solution, I'm deliberately not going to give it to you (and I hope that by bumping the question to the front page I don't cause someone else to) because in my opinion the point of challenge websites is for you to learn by doing, and you will learn more effectively by figuring it out yourself with hints than by getting the solution on a plate. However, I do have some comments on your code.

class Solution:
    # @param A : list of strings
    # @param B : integer
    # @return an integer

It's useful to document the expected type, but it's more useful to document the meaning. Here B is the K of the problem specification, but I shouldn't have to work that out myself. The parameters would benefit from descriptive names, and the @return should outline what the integer returned means.

    def LCPrefix(self, A, B):
        res = 0
        for i in xrange(len(A)):
            prev = A[i]
            prevLCP = len(A[i])
            for j in xrange(i, len(A)):
                prevLCP = self.getLCP(prev, A[j], prevLCP)
                prev = A[j]

There's a possible minor optimisation here: when j == i you already know the LCP, but you calculate it again. In my opinion it would be worth duplicating the simple test if prevLCP >= B: res += 1 before the loop, and only considering j > i. As a bonus, you would no longer need to track prev because you would always be testing the common prefix of A[j-1] and A[j]. (Hint: does that give you any ideas for optimisation?)

Why the update to prevLCP? I can figure it out, but a comment (and a better name - because the value of prevLCP isn't the previous LCP) would be useful.

                if prevLCP >= B:
                    res += 1

An else: break clause here would not change the asymptotic complexity of your solution, but it would surely make it much faster in many test cases.

        return res % 1000000007

I'll give you one more hint about improving the complexity: the fact that they want the answer modulo 109 is a really big clue that you shouldn't compute it solely via res += 1.

    def getLCP(self, A, B, upto):

Document the parameters, and think about the names. getLCP implies to me that the return value should be the longest common prefix: i.e. a string. But it's actually an integer, and it might not even be the length of the LCP because of upto.

        i = 0
        lim = min(upto, len(B))
        while i < lim:
            if A[i] != B[i]:
                break

            i += 1

        return i

In the other method you used xrange: why not here?

        lim = min(upto, len(B))
        for i in xrange(lim):
            if A[i] != B[i]:
                return i
        return lim


Crawling for emails on websites given by Google API

As @tokland pointed out, the major thing that jumps out when reading your code is the indentation problems. In most Ruby code you see, the standard indentation is 2 spaces. It looks like you are using hard-tabs, which are generally a bad idea. You should explore the settings of your text editor -- most have an option to insert spaces instead of tabs when you press the "tab" key. Here is your code would look like if indented properly:

require "nokogiri"
require "json"
require 'mechanize'
require 'anemone'
require "typhoeus"
require "timeout"

class String
  def to_bool()
    return true if self == "true"
    return false if self == "false"
    return nil
  end
end

class Query
  def initialize(keyword)
    10.times do |n|
      num = (n * 10 + 1).to_s
      p num
      req = Typhoeus::Request.new("https://www.googleapis.com/customsearch/v1?key=[my_key]&cx=018020274830505137072:utuofm0ugh0&q=" + keyword + "&start=" + num, followlocation: true)
      res = req.run
      File.open("file.json","w") do |file|
        file.write(res.body)
      end
      continue = "true"
      fs = File.read("file.json");
      string = JSON.parse(fs);
      string["items"].each do |item|
        p continue.to_s + "<- item"
        begin
          Anemone.crawl("http://" + item["displayLink"] + "/") do |anemone|
            anemone.on_every_page do |page|
              if continue.chomp.to_bool == false
                raise "no more please"
              end
              request = Typhoeus::Request.new(page.url, followlocation: true)
              response = request.run
              email = /[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}/.match(response.body)
              if email.nil?
              else
                p email
                begin
                  continue = Timeout::timeout(2) do
                    p "insert now false/nothing"
                    gets
                  end
                rescue Timeout::Error
                  continue = "true"
                end
              end
            end
          end
        rescue Exception => e
          p e
          continue = "true"
          next
        end
        p "---------------------------------------------------------"
      end
      p "new request"
    end
  end
end

qs = Query.new("texas+web+development")

For your to_bool() function, this might be a little nitpicky, but I would rewrite it as a case statement like this:

class String
  def to_bool()
    case self
      when "true"; true
      when "false"; false
      else; nil
    end
  end
end

The URL you're passing to Typhoeus::Request.new is ratehr long. You might consider doing something like this to shorten your line lengths a little:

base_url = "https://www.googleapis.com/customsearch/v1?key=[my_key]&cx=018020274830505137072:utuofm0ugh0&q="
req_url = base_url + keyword + "&start=" + num
req = Typhoeus::Request.new(req_url, followlocation: true)

Or, if you want to be really diligent about not having long lines, you could do this:

base_url = "https://www.googleapis.com/customsearch/v1"
key = "[my_key]"
cx = "018020274830505137072:utuofm0ugh0"
req_url = "#{base_url}?key=#{key}&cx=#{cx}&q=#{keyword}&start=#{num}"

You have a part of your code that goes if email.nil? (nothing) else (something). A better way to put this would be:

unless email.nil?
  p email
  # etc.

As a general note, you could make your code more concise by using less "intermediate" or "throw-away" variables. Take advantage of Ruby's method chaining and try condensing your code like this:

...

# No need to define a variable res; req.run is short enough
req = Typhoeus::Request.new(req_url, followlocation: true)
File.open("file.json", "w") do |file|
  file.write(req.run.body)
end

...

# You can get rid of the fs and string variables and do this:
JSON.parse(File.read("file.json"))["items"].each do |item|
  p continue.to_s + "<- item"
  # etc.

...

# You could change the name of the variable from request to req,
# for consistency -- you named another Typhoeus request "req"
# earlier in the code, and it doesn't look like you still need
# that variable, so there's no harm in re-using the name "req."

# Notice how you can eliminate the need for the variables "response"
# "email" like this:
req = Typhoeus::Request.new(page.url, followlocation: true)
email_pattern = /[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}/
unless email_pattern.match(req.run.body).nil?
  # etc.

You might consider changing if continue.chomp.to_bool == false to unless continue.chomp.to_bool, or even if continue.chomp == "false". In fact, I think I like the last way the best -- you could totally do away with monkey-patching a String#to_bool method and just compare continue.chomp to "true" or "false". It's your call, of course. :)

Lastly, this is just my 2 cents, but I think you could simplify the way you're using continue. If I'm understanding correctly, it starts as "true" and you want the program to keep running unless the user types "false" when prompted. I would consider doing away with your String#to_bool method and just comparing whether or not continue.chomp.downcase equals "stop", "exit" or "quit". You could do something like this:

stop_words = ["stop", "exit", "quit"]
continue = ""

...

if stop_words.include? continue.chomp.downcase
  raise "no more please"
end

This would save you from having to keep doing continue = "true" to make sure the program doesn't stop. As long as the value of continue.chomp.downcase is not one of the stop words, the program will keep running.

I admit, though, that I don't really understand the use of continue in p continue.to_s + "<- item", so maybe there is something I'm missing.

Anyway, hope this helps!


Program to generate numbers, finding average and largest values and rounding the largest to 100

Just a quick approach. It could be improved more. What you want is a way to reduce the two loops into one.

Some comments about the code: We initialized imax in order to reduce the if -else statement and also we combined the 2 foor loops in the end into one. What I would like to achieve even more is to reduce the final two for loops into one. But I think this is not possible for this case. But I might be wrong.

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    int sum = 0, imax = 0;
    int puan[10];
    srand(time(NULL));
    for(int i=0; i<10; i++)
    {
        puan[i]=rand()%101;
        printf("%d. ogrencinin notu = %d \n",i+1,puan[i]);
        if(puan[i]>imax)
        {
            imax=puan[i];
        }
        sum += puan[i];
    }
    float avg=sum/10.0f;
    int fark = 100 - imax;
    printf("\nEn yuksek not = %d ve not ortalamasi %f.\n",imax,avg);
    printf("Her ogrencinin notuna %d puan eklendi.\n\n",fark);
    for(int i=0;i<10;i++)
    {
        puan[i] += fark;
        if(puan[i]<avg)
        {
                printf("%d. ogrenci aldigi %d notuyla ortalamanin altinda kalarak dersten basarisiz olmustur.\n",i+1,puan[i]);
        }
    }

    return 0;
}


Can I improve my jquery dialog code, critisicm welcome

In JavaScript it is custom to give functions names that start with a lowercase letter so that they are not confused with objects.
Personally I'd avoid "hardcoding" the connection of the id of the link with the id of the dialog. (login -> login_dialog). Instead you could use the href of the link to refer to dialog. Example:

login

var dialog = $(this.href.replace(/.*(?=#[^\s]*$)/, ''));

(The replace is necessary due to bugs in IE < 8)

You are repeatedly assigning the click and resize event handler on each click, so that each time a dialog is shown a additional handler is added, but never removed.

(There is more, however I don't have time right now. Maybe I'll come back later)


In general, I think that's a great start - it's consistently formatted and sensibly structured.

def initial_of_name(c):

c isn't a great name for a parameter, it tells the reader nothing about what the function is expecting to get. It might also be helpful to add a docstring to provide a bit more information.

word_list = c.split(" ")

If you're splitting on spaces, note that you can just use .split(), which will also have the effect of counting consecutive whitespace as a single space. This is helpful if someone accidentally types My  Name instead of My Name; with the current formulation you'd get ['My', '', 'Name'].

i = (len(word_list) - 1)
...
for w in range(0, i):
    word = word_list[w]

Iterating over a list by index in Python is a bit of an anti-pattern, there are lots of better tools for dealing with iteration. In this case, you could iterate over a slice of all but the last item in the list:

for word in word_list[:-1]:

Talking of slicing:

word = word[0:1].upper()

You don't need the 0, that's the default start to a slice, so it could be word[:1]. But what you want is the first character, which is perhaps more clearly expressed as word[0].

new_list = []
for ...:
    ...
    new_list.append(...)

Creating an empty list, iterating and appending is often not the most efficient way to build a new list. Instead, consider a list comprehension (if this is unfamiliar to you, see e.g. Python for-in loop preceded by a variable).

print("The initial of your name is {0}.".format(initial))

In general, I wouldn't use print in a function like this. This is part of separation of concerns; building the appropriate string and displaying the result to the user are two completely different tasks, so they shouldn't be in the same function. Additionally, printing rather than returning the result makes it harder to test the function.

With all of that considered, here's how I would implement the same requirements.

def initial_of_name(name):
    """Converts a name to initials and surname.

    Ensures all initials are capitalised, even if the
    first names aren't.

    Examples:

      >>> initial_of_name('Ram Chandra Giri')
      'R.C.Giri'
      >>> initial_of_name('Ram chandra Giri')
      'R.C.Giri'

    """
    parts = name.split()
    initials = [part[0].upper() for part in parts[:-1]]
    return '.'.join(initials + [parts[-1]])

if __name__ == '__main__':
    name = input("Please enter your name?\n>")
    initial = initial_of_name(name)
    print("The initial of your name is {0}.".format(initial))

If the last part is unfamiliar, see What does if __name__ == "__main__": do?

Note that including examples in the docstring in the form of an interactive Python session not only gives the reader a good idea of exactly how to use the function, but also allows doctest to validate the code and examples for you. If you save the above into a file initial.py:

$ python -m doctest initial.py --verbose
Trying:
    initial_of_name('Ram Chandra Giri')
Expecting:
    'R.C.Giri'
ok
Trying:
    initial_of_name('Ram chandra Giri')
Expecting:
    'R.C.Giri'
ok
1 items had no tests:
    initial
1 items passed all tests:
   2 tests in initial.initial_of_name
2 tests in 2 items.
2 passed and 0 failed.
Test passed.


Secure math expressions using PHP eval()

It looks pretty reasonable to me. A couple of points:

You seem to be assuming that a function start with a letter. Functions CAN start with an underscore. Are you sure there is no such function that can be exploited?
The regex in the section 'Invalid function calls' seems like it could be simpler. You are trying to check that any 'word' ends with a '(', is this right? If so, I don't think you need the second \w

Finally although this seems like a good job, the ideally ideal way to do something like this would be to make your own tokenizer. A tokenizer looks at a string char by char and decides at each point whether it's looking at part of an identifier, an operator, etc. You would simply need to call your checks at each point that it decides it has identified a complete token. The advantage of this is that it would be easy to extend the syntax you accept and if needed to make translations from the language you accept to valid PHP for eval().


Simulating the radioactive decay of atoms using a random number generator

Firstly, some minor nitpicks on your code:

   for (int i = remainingAtoms; i > 0; i--) {

Why are you counting down instead of up? I can see why after careful inspection, but a comment would be useful.

        println ("There are " + (atomicRed (nAtoms)) + " atoms at the end of year " + nYears);

You've violated Command-Query Seperation. atomicRed changes the state of the object, and so it really shouldn't return information about the object. It certainly shouldn't appear in the middle of a print a call.

        boolean isReduced = rGen.nextBoolean();
        if (isReduced) nAtoms--;

Why did you seperate isReduced onto its own line?

As for your actual question: people differ on this point. My general theory is that seperating out functions is good. But don't move previously local variables to the class in order to do that. Doing so only makes your class harder to follow.

In this case, I suggest something like

while(nAtoms > 0)
{
     nAtoms = remainingAtomsAfterYear(nAtoms);
     println("There are " + nAtoms + " atoms at the end of year " + nYears);
     nYears++;
}

This allows you to pull the logic regarding atom decay into a separate function, but avoids storing state on the class. I think this actually gets the best of both approaches.

Alternately, you could do:

while(!atoms.empty())
{
    atoms.simulateYear();
    println("There are " + atoms.count() + " atoms at the end of year " + atoms.years());
}

And move all the logic into another class. That's overkill here, but is helpful if the state gets more complicated.


An alternative to loop constructs in Java

In Java 8 you can use streams, they tend to make the code quite more compact:

IntStream.range(0, 5).forEach(i -> System.out.println("Hello World!"));

I would recommend reading the documentation of IntStream and Streams in general


The only simplification I can think of is using a bit more complex regex to match the IP address without having to iterate over the octets:

def valid?(proxies)
  return false if !proxies.is_a?(Array) || proxies.empty?
  ipv4_address = /^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d):\d+$/
  proxies.each do |proxy|
    return false if proxy !~ ipv4_address
  end
  true
end

This regex is based on the one in the ipaddress package.


Review internet connection pinging method

Some comments, mostly minor:

I would extract the
server connection to a function:

static int connect_server(const struct addrinfo *host_info)
{
    struct addrinfo *host_info_list;
    int fd = -1;
    int status = getaddrinfo(...);
    while(...) {
        fd = socket(...);
        status = connect(...);
    }
    freeaddrinfo(host_info_list);
    return fd;
}

All that DEBUG stuff is distracting.  Maybe it is temporary, but if you
wanted to leave it in, I suggest extracting it:

#include <stdarg.h>

static inline void debug(const char *format, ...)
{
#ifdef DEBUG
    va_list ap;
    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
#endif
}

and calling it:

debug("Bytes recieved: %ld\n%s\nReceiving complete. Closing socket...\n",
      bytes_recieved,
      incomming_data_buffer);

If DEBUG is undefined, the inline debug function will be empty and will
be excluded during compilation - it disappears.

You clearly need to loop to read the whole message...  After reading you
throw away the last two bytes.

buffer[bytes_recieved - 2] = '\0';

The recv call filled the buffer, so to \0 terminate properly you need to
specify a smaller buffer:

char buffer[1000];
ssize_t bytes_recieved = recv(socketfd, buffer, sizeof buffer - 1, 0);
...
if (bytes_recieved > 0) {
    buffer[bytes_recieved] = '\0';
}

Note the use of sizeof instead of an explicit 1000

And some other things...

The man-page for getaddrinfo suggests looping through the list of
addresses returned instead of just using the first (in case the first does
not work).
When something fails you should exit rather than continuing.
instead of using strlen on a constant string, use sizeof:

const char msg[] = "GET / HTTP/1.1\nhost: www.google.com\n\n";
ssize_t bytes_sent = send(socketfd, msg, sizeof msg - 1, 0);

note the msg[], not *msg
perhaps use perror or strerror on failure to read etc.
camelCase function name but separate_word names elsewhere.


Not a full review, just a couple of points that jumped out at me:

you often assign the value to a variable on the next line after declaring it. Just assign the value on the same line (eg int startRange = nextValidInt(input);).
you can declare a loop variable inside the loop: for (int numberOfTries = 0; numberOfTries <= maxAttemp - 1; numberOfTries++).
if (numberOfTries >= maxAttemp) will always be true, as the for loop increases numberOfTries to maxAttemp. Well, except when you won. I would remove the if and replace the break with a return.
numberOfTries <= maxAttemp - 1 looks better written as numberOfTries < maxAttemp.
the main method shouldn't do anything except start your program. I would move your code to its own function. You might also want to create extra functions for initial info printing/setup gathering and the actual guessing game.


What is the potential risk with this code?

Update

OP has since updated question so this answer makes no sense any more WRT question asked!! Those edits have also been lost in migration from stack overflow it seems.

Purely from a concurrency perspective and not commenting on if the design is fit for purpose:

Newly added Volatile

You do not understand this, I am not going to go into why, just read up on stack overflow/MSDN or don't use it. As I remember you had a readonly on the instance. That was correct.

In general don't lock(this), because (although not in this case... yet) this can also be locked from external code (lock(BarrierCount.getInstance())), and that allows deadlocks to occur. Although no deadlock is possible here as the methods are guaranteed to return.

Instead add a specific lock object:

private readonly object _lock = new object();

Note

readonly not volatile. readonly makes it clear to readers/modifiers that the reference is safe to use from multiple threads. It also stops modifiers from changing the reference (unless they remove the readonly, but they should make them think twice at least).

In WaitForAll you read count without a lock. Suggest you add a private GetCount() which locks.

I'm not sure how this is used, the setCount is presumably called once before the work commences. If the tasks have started and there is any risk in them calling workDone before setCount then it won't ever reach zero.

I would loose setCount in favour of an IncrementCount() method called before starting each task.

But

You should look at Task.WaitAll before you do more on this.


Searching a huge number of strings from Excel to a large number of Text files

A few suggestions:

Most obvious (and simple) step is to read the entire file, and not one line at the time

Change this:

Set file = fso.OpenTextFile(Path)
Do While Not file.AtEndOfLine
    Line = file.ReadLine
    If InStr(1, Line, theString, vbTextCompare) > 0 Then
        ws2.Cells(K, 4).Value = Str
        ws2.Cells(K, 5).Value = fname
        ws2.Cells(K, 6).Value = "Srting is found"
        flag = "Y"
    End If
Loop

To this:

Set file = fso.OpenTextFile(Path)

fullFile = file.ReadAll

If InStr(1, fullFile, theString, vbTextCompare) > 0 Then
    With ws2
        .Cells(K, 4).Value2 = theString
        .Cells(K, 5).Value2 = fname
    End With
    flag = "Y"
End If

It eliminates the do-while loop. More details about .ReadAll().
Store Str and fname info into an array, then commit the entire array to the worksheet at the end, instead of writing to each cell separately.
The "Find" command in DOS might be faster and it can also provide the line number(s) where the string is found:

Find /?

Searches for a text string in a file or files.

FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]


You're not using StringBuilder effectively.  If you already have sb, then why not do sb.append(b).toString() instead of sb.toString() + b?  If you look at the generated bytecode for sb.toString() + b, you'll see that it actually makes another StringBuilder for you, like new StringBuilder(sb.toString()).append(b).toString().

I would write it this way instead, with no special cases:

public static String equalConcatentation(String a, String b) {
    int len = Math.min(a.length(), b.length());
    return a.substring(a.length() - len) +
           b.substring(b.length() - len);
}

I've chosen to make it a static method because it's purely a function of the two input strings, not using any object state.


Reset files in Git which show as modified but have no changes according to “git diff”

The slowness

The slowness most probably comes from executing multiple git diff commands.
A faster way might be using a programming language with a Git library that would let you run a single git diff command,
and iterate over the entries of the diff to find the empty ones.

The hacky part

This is hacky:

git status | grep "modified:" | cut -c 14-

The output of the git status is not API,
and may also be subject to aliases and user settings.
It's not safe to use.
When parsing the output of Git commands,
look for a --porcelain option to make it safe.

Another hacky part is changing the value of IFS.
It's not a huge problem,
but it's good to minimize the scope of the change,
typically by using it in the form of IFS=... cmd,
which would limit the effect of the change to the execution of the cmd command.

Lastly, some minor style issues:

The $gitDiffStr variable is pointless, you can simply inline it.
The == operator within a [ ... ] is undocumented. Use = instead.

Alternative implementation

Applying the above suggestions, this is less hacky, and probably just as slow:

git status --porcelain -z | grep -z '^ M' | while IFS= read -r -d '' path0; do
    path=${path0:3}
    gitDiff=$(git diff "$path")
    if [ "$gitDiff" = "" ]; then
        echo git checkout "$currentFile"
        git checkout "$currentFile"
    fi
done


.equals

The last part of your .equals implementation can be simplified to:

return Objects.equals(this.path, other.path) && Objects.equals(this.fileTime, other.fileTime);

HashCode

int hash = 3;
return hash;

Do I even have to comment anything about what I think about this implementation? You use Objects.equals above, you can use Objects.hashCode(this.path, this.fileTime); here. It is preferred if hashCode and equals use the same fields for their operations.

Set or List?

Whenever you use a List in a program, ask yourself the question: Does the order of the elements matter?

In this case, they don't. Use the Set interface and create as HashSet for your elementsInProcess variable.

private final Set<E> elementsInProcess = new HashSet<>();

When using a Set, it is extra important that the elements in the set has properly implemented hashCode and equals! (Or are using the default implementations inherited from the Object class)

Cleanup

I suggest you override the shutdown methods of a ThreadPoolExecutor to clear the elementsInProcess collection.

execute(Runnable command)

Please throw a UnsupportedOperationException or similar in this method:

public void execute(Runnable command) { }

Edit: Scratch that. I think palacsint is absolutely right. By doing nothing here, you're breaking the contract of the Executor interface (which you implement, whether you know it or not - by extending an ExecutorService). The Javadoc for the execute(Runnable command) method says:

  Executes the given command at some time in the future.

As it currently stands, you are not doing that and have no real ability of doing so in that method. This fact is an indication that you should not use extends ThreadPoolExecutor and instead use a private ThreadPoolExecutor executor;, and therefore using composition over inheritance.

Concurrency

If two threads would call execute at the same time, there is a concurrency issue on elementsInProcess. You need to synchronize on something there, for minimal blocking I suggest you do something like this:

synchronize (lock) {
    if (elementsInProcess.contains(element)) {
        return;
    }
    elementsInProcess.add(element);
}
super.execute(() -> consumer.accept(element));

Where lock is a private final Object lock = new Object();

Or, you could utilize the fact that the .add method of a set actually returns a boolean indicating if the add was successful and use a Collections.synchronizedSet.

if (!elementsInProcess.add(element)) {
    return;
}
super.execute(() -> consumer.accept(element));

It is important when using a synchronized Set that you only do one method call here, as there could otherwise be a gap between .contains and .add which would again cause concurrency issues between threads.


Naive Bayes classifier for OKCupid profiles

#!/usr/bin/python

# Naive Bayes classifier for OkCupid data.  The features are the words in
# the profile and the classes are HIGH and LOW.  This is used to
# predict the rating I would give a profile.

# TODO: tweak the classifier so it works better.

from subprocess import call
from math import sqrt

# File containing training data in the form "<rating> <username>"
TRAINING_DATA = "train.dta"

# File containing test set in the form "<rating> <username>"
TEST_DATA = "test.dta"

# Dictionary
dictionary = "TWL06.txt"

Why is this not in ALL_CAPS like the others?

# Hash table containing words in highly-ranked profiles.
HIGH_WORDS = {}

# Hash table containing words in low-ranked profiles.
LOW_WORDS = {}

These aren't constants, so they shouldn't be global or in ALL_CAPS

# Number of users in each category
hi = 0
low = 0

Once you actually start logic, its best to do it inside a function except for really simply scripts.

# Add training data to the hash tables.
t = open(TRAINING_DATA, 'r')

Don't use single letter variable names, it results in difficult to follow code. Also, you should open a file using the with statement, to make sure it closes in all circumstances.

for user in t:
    rating = int(user.split(" ")[0])
    name = user.split(" ")[1]

Why are you passing the " " to slit instead of trusting the default. This approach is a little wasteful because you split the input twice.

    # Count users
    if rating == 1:
        hi += 1
    else:
        low += 1

    # Get data for each user
    call(["curl", "-o", "tmp.dta", "http://www.okcupid.com/profile/" + name])

Use urllib.urlopen to fetch urls. That you can avoid the temporary file.

    d = open("tmp.dta", 'r')

    # Get word list from user
    words = {}
    for line in d:
        for word in line.split(" "):
            if "/" in word or "=" in word or "<" in word or ">" in word or "()" in word or "&" in word or len(word) > 10:

Make a list of blocked characters rather then duplicating your logic so much here. And I suspect that "()" in word wasn't what you wanted.

                continue

I try to almost always avoid continue. I suggest rewriting the logic so the following line in the if block.

            words[word.rstrip().lower()] = None

You seem to be using words as a set. Use a set.

    d.close()

    # Add words in this word list to our master word lists
    for word in words:
        if rating == 1:
            if word in HIGH_WORDS:
                HIGH_WORDS[word] += 1
            else:
                HIGH_WORDS[word] = 1

Look at collections.Counter to simplify this.

        else:
            if word in LOW_WORDS:
                LOW_WORDS[word] += 1
            else:
                LOW_WORDS[word] = 1
t.close()

print HIGH_WORDS
print LOW_WORDS

# Classify a point, assuming training has already happened.
# P(C | F1 ... Fn) proportionate to P(C) * P(F1 | C) * ... * P(Fn | C)
def classify(username):
    # P(C)
    Phi = float(hi) / float(hi + low)
    Plow = float(low) / float(hi + low)

Add from __future__ import division so that all division produce floats. Then you don't have to cast to float. I also suggest calling the variable: probaility_high for greater clarity.

    ratio = Phi / Plow
    # Get data
    call(["curl", "-o", "tmp.dta", "http://www.okcupid.com/profile/" + username])
    d = open("tmp.dta", 'r')
    for line in d:
        for word in line.split(" "):

There is some duplication here. You should be able to write a function that returns the words from the url.

            # Calculate the probability of the feature given a class
            if word in HIGH_WORDS:
                numHi = float(HIGH_WORDS[word])
            else:
                numHi = 1
            if word in LOW_WORDS:
                numLow = float(LOW_WORDS[word])
            else:
                numLow = 1

            ratio = ratio * (numHi / float(hi)) / (numLow / float(low))
#            if word in HIGH_WORDS:
##                Phi = Phi * float(HIGH_WORDS[word]) / float(hi)
##            else:
##                Phi = Phi * (1 / float(hi))
#
#            if word in LOW_WORDS:
##                Plow = Plow * float(LOW_WORDS[word]) / float(low)
##            else:
##                Plow = Plow * (1 / float(low))

Don't leave dead code. Delete it.

    print ratio
    if ratio > 1:
        return 1
    else:
        return 0

# Compute out of sample error on test set.
def getError():
    t = open(TEST_DATA, 'r')
    numUsers = 0.0
    total = 0.0
    for line in t:
        user = line.split(" ")[1]
        rating = int(line.split(" ")[0])
        prediction = classify(user)
        numUsers += 1.0
        if rating != prediction:
            total += 1.0

Total seems a confusing name, because its only the mismatches.

        print str(rating) + " " + str(prediction) + " " + user

    return total / numUsers

print getError()

You may want to look into numpy. It'll allow much more efficient operations on large amounts of data like this.


The first bad thing you do is a lot of string concatenations like

_outputGrid += "1";

which cause many memory reallocations. Since during one game grid size is a constant number you can save it at the constructor, and then just create array for result and set its elements by index.

_outputGrid = new char[_gridSize * _gridSize];
...
_outputGrid[currentIndex] = '0';

At the end of the CalculateNextGrid method convert this array to string and return it:

return new string(_outputGrid);

I suggest to use array of bool's as internal storage for result instead of a string. In my opinion true and false represent the state of a cell (alive or dead) more clearly. You can even use array of enum values like:

public enum CellState
{
    Alive,
    Dead
}

_outputGrid[currentIndex] = CellState.Alive;

You can go further and create method like:

private void ReviveCell(int index) => _outputGrid[index] = CellState.Alive;

It would be better to extract magic conditions to some methods like:

private static bool ShouldBeDeadByUnderpopulation(int count) => count < 2;

private static bool ShouldBeDeadByOverpopulation(int count) => count > 3;

and so on.

And instead of condition like

if (inputGrid[currentIndex + _up    + _right]   == '1')

use methods too

if (IsAlive(value))

With all these changes your code will look like a story where all is clear :)

if (IsAlive(currentCell))
{
    if (ShouldBeDeadByUnderpopulation(_cellCount ) ||
        ShouldBeDeadByOverpopulation(_cellCount))
    {
        KillCell(currentIndex);
    }
    else
    {
        // Note that this code is redundant since cell is alive at the moment
        ReviveCell(currentIndex);
    }
}


Natural sorting/comparing algorithm in TypeScript

Dead code

interface NaturalSortConfig {
    keyFunc?: NaturalKeyFunc;
    //desc?: boolean;
    //caseInsensitive?: boolean;
}

Dead code does nothing, except take up screen space, and confuse people who don't know why it was written and removed in the first place.

Braces

This is a bit of a holy-war.  However, at least one bug (the Apple SSL bug) was caused by missing braces.  Personally, I use them:

if (typeof a === "number" && typeof b === "number") {
    return a - b;
}

Instead of:

if (typeof a === "number" && typeof b === "number")
    return a - b;

Functions

You may want to consider splitting this into more methods.  One possible method might be to move the code to determine whether to early-return into its own function:

function IsValidData (o) {
    return o === null || o === undefined || Array.isArray(o);
}

Most of the code in naturalSort() is duplicated - more functions would really help here.

Early exit

As mentioned in the comments in the previous (deleted) answer, you can early-return as soon as you know which value is sorted higher.  For example, sorting "aa" against "bb" should be able to return after checking the first character of each, while "aaa" vs. "aba" should be able return after checking the second, and so on.


Locating the largest Collatz Sequence with memoization

Heap size

  The idea was to cache the sequence lengths for as many sequences as possible, from 0 to some value. I managed to (on my PC) get that value up to 1427500000, which is a large number.

When I try it with the same value, I run out of heap space.  That may be fixable by changing my JVM settings.

Optimizing by combining steps

                    if (currentNumber % 2 == 0) {
                        currentNumber = currentNumber / 2;
                    } else {
                        currentNumber = 3 * currentNumber + 1;
                    }
                    chainSize++;

You say that you found that it was faster if you divided by 2 in the else as well, but it gives inaccurate chainSize values.  Have you considered

                    if (currentNumber % 2 == 0) {
                        currentNumber /= 2;
                        chainSize++;
                    } else {
                        currentNumber = (3 * currentNumber + 1) / 2;
                        chainSize += 2;
                    }

This should give an accurate chainSize value if I'm understanding the optimization properly.

Also, this uses the briefer /= notation where i /= 2; has the same value as i = i / 2;.

Or

                    if (currentNumber % 2 != 0) {
                        currentNumber = 3 * currentNumber + 1;
                        chainSize++;
                    }

                    currentNumber /= 2;
                    chainSize++;

I'll leave it up to you if these help with run time as well.

Don't do useless checks

You have

                if (currentNumber > largestNumberAnyChain) {
                    largestNumberAnyChain = currentNumber;
                }

separate from the currentNumber update.  However, in two of the three branches, you reduce the value of currentNumber.

Consider what happens if you move it into the previous code.

                    if (currentNumber % 2 != 0) {
                        currentNumber = 3 * currentNumber + 1;
                        chainSize++;

                        if (currentNumber > largestNumberAnyChain) {
                            largestNumberAnyChain = currentNumber;
                        }
                    }

                    currentNumber /= 2;
                    chainSize++;

This is the only branch where currentNumber increases, so it's the only one that needs checked.

You could also move the check for negative numbers here for the same reason.  Note further that the largest check and the negative check will never be true at the same time.

Avoid timing output

                System.out.println("New best: " + maxNumber + " at " + maxLength + " chains in " + ((double)(System.nanoTime() - startTime) / 1000000000) + "s.");
            }

            if (i % (maxTestValue / 100) == 0) {
                System.out.println("At " + i + " of " + maxTestValue + " (" + (i / (maxTestValue / 100)) + "%) in " + ((double)(System.nanoTime() - startTime) / 1000000000) + "s");
            }
        }

        System.out.println("Best: " + maxNumber + " at " + maxLength + " chains.");
        System.out.println("Largest number in any chain: " + largestNumberAnyChain);
        System.out.println("Took: " + ((double)(System.nanoTime() - startTime) / 1000000000) + " seconds.");

If you write this instead as

            }
        }

        double elapsed = (double)(System.nanoTime() - startTime) / 1000000000;
        System.out.println("Best: " + maxNumber + " at " + maxLength + " chains.");
        System.out.println("Largest number in any chain: " + largestNumberAnyChain);
        System.out.println("Took: " + elapsed + " seconds.");

You might find that it runs faster.

Same problem with

                        System.out.println("Value from chain " + i + " at length " + chainSize + " is negative: " + currentNumber);

Measuring the time it takes to do the output distorts the overall timing.  It may not matter here, but it can be a bad habit to develop.


It is usually considered bad practice to use * imports.  Be specific about your dependencies.
Don't use root DB access for your application.  That should truly be reserved for a root DB user.  Create a MySQL user for the application with appropriate privilege levels.
Don't hard code your DB credentials into your code.  This should ideally be derived from application or environmental configuration.
Should you really be swallowing up your exceptions like this?
Your validation against NPE's seems odd here. Rather than a pattern like

this:

try {
    if(con != null) {
        con.close();
        System.out.println("Database Connection Closed!");
    }
}catch(Exception e) {
    e.printStackTrace();
}

perhaps you should be doing something like:

if(con == null) {
    throw new NullPointerException('...');
}
// rest of code in method. Now, without need to be nested in conditional

But you should definitely let the caller know if they passed you a null pointer vs. swallowing it.

I find it very odd to be opening prepared statements and result sets in your Source class but closing them using the DBUtil class. This seems very asymmetric to me and a leaking of responsibility outside the class.
Don't get yourself into the bad habit of using SELECT * queries.  They can be wasteful of bandwidth (by pulling unnecessary fields from DB into application), they can obfuscate the data structure that is being worked in within the code (i.e. you have to go look at the table in the database to understand what fields you are working with), and it can make your code fragile to table schema changes
getInput() is a bad method name.  This method is actually both reading in user input and inserting data in the database, something that is not implied from the method name, and activities that should probably be split into individual methods.  The same could be said about displayData(). This method is not just displaying data, but also retrieving it from the database.
Consider passing the database connection and the scanner to the Source class as dependencies rather than having the class have to hold the knowledge on how to set them up. Of course, this might require a larger thought shift towards dependency injection throughout other areas of code.
I know this is a bit of a trivial example, but why would the constructor for the class trigger both the input and ultimate display of content?
I don't see the need to have class properties for storing the prepared statement and result set objects.
You don't use dbConnection class property at all. There is probably no need for even storing the connection if you aren't going to reference if across different methods - something not happening the way this class is currently designed.
I see no need to actually connect twice to the database here, especially considering this class is really designed for the purpose of doing one single operation that is really more procedural in nature.
When building classes in the future, begin to think about how to separate class functionality from end user messaging or view output.  Again, I know this is a simple example, but the more you do this in the future, the more you are better able to make your classes re-usable..


Project Euler #14: Longest Collatz Sequence starting point

Integer Division

In Python, 10 / 2 is equal to 5.0, not 5.  Python has the integer division operator (//) which produces an integral value after division, instead of a floating point value.  To prevent storing both int and float keys in the count dictionary, you should use:

    count[n] = collatz_count(n // 2) + 1

Cache

Your count cache works nicely.  But you don’t have to implement it yourself.  Python comes with caching built-in.  You just have to request it.

import functools

@functools.lru_cache(None)
def collatz_count(n):
    if n == 1:
        return 1
    elif n % 2 == 0:
        return collatz_count(n // 2) + 1
    else
        return collatz_count(n * 3 + 1) + 1

The first time collatz_count(n) is called with any particular value of n, the function is called and the returned value is memorized in the cache.  Any subsequent call with that argument retrieves the value from the cache.  (The None value indicates that the cache size is unlimited.)

Sorting to find the maximum

Sorting, in order to find the maximum value, is an \$O(n \log n)\$ in time, and since you need to remember all the values, \$O(n)\$ in space.

There is no need to sort the list; instead, just maintain the largest value encountered so far, and the input which generated that value.  This is \$O(n)\$ in time, so much faster, and \$O(1)\$ in space.

And again, it is built-in to Python:

longest_start_number = max(range(1, 1000000), key=collatz_count)
length = collatz_count(longest_start_number)

Docstrings

You are using the docstrings incorrectly.

You shouldn’t say """uses the previous function ...  """ in a docstring, because if a user types help(run_test), they will not know what function the previous function is.  Even if they type help(module_name) and get help for all the functions in the module, the order the functions get listed in the resulting help output is not necessarily the order of the functions in the module’s source, so again “the previous function” is confusing.

Similarly, saying """uses cache (count) to speed up ...""" is useless, because a user typing help(collatz_count) is expecting to find help on how to use the function, such as what legal values can be given for n, what the return value is, and whether or not the user is expected to pass in a value for count; they don’t need implementation details about how the function was written.


Your code looks pretty good for a newcomer to the language. Some comments:

I don't quite understand why you need uni.
References to t[0] and t[1]: It's more declarative to unpack tuples/lists and give names to its components -> something, another_thing = t
for i in range(int(f.readline())). I won't say this is bad, but certainly not very declarative. Note that itertools.islice can be used to read N lines from a file object -> itertools.islice(f, 10).
Python2: Unless you have a compelling reason, use Python 3.
reduce(lambda.... As much as I like functional style, code that uses reduce with long lambdas usually looks cryptic. But I think it's still ok to use reduce with named functions.
int(f.readline()). Personally I like to give names to values when it's not clear what they stand for. Granted, this may increase the LOC slightly, but I think it's worthwhile. In this case, if we write number_of_queries = int(f.readline()) and later use the variable, it's easy to see what's going on.

As a first refactor, I'd write:

import itertools
import functools

lines = open("input.txt")

# Parse associations
n_associations = int(lines.readline())
associations = {}
for line in itertools.islice(lines, n_associations):
    n, associations_string = line.split(":")
    associations[n] = set(associations_string.split())

# Parse and run queries
n_queries = int(lines.readline())
for line in itertools.islice(lines, n_queries):
    numbers = line.split()
    common = functools.reduce(set.intersection, (associations[n] for n in numbers))
    print(" ".join(common))

Ok, now let's take it a step further. Firstly, there are no functions at all, no modularization, that's no good. Secondly, I prefer a functional approach and there is some imperative stuff going on there. That's how I would write it in a more functional and declarative style:

def parse_and_execute_queries(path):
    def parse_association(line):
        number, associations_string = line.split(":")
        return (number, set(associations_string.split()))

    def execute_query(associations, query_string):
        numbers = query_string.split()
        common = functools.reduce(set.intersection, (associations[n] for n in numbers))
        return " ".join(common)

    lines = open(path)
    n_associations = int(lines.readline())
    association_lines = itertools.islice(lines, n_associations)
    associations = dict(parse_association(line) for line in association_lines)
    n_queries = int(lines.readline())
    queries_lines = itertools.islice(lines, n_queries)
    return (execute_query(associations, line) for line in queries_lines)

for query_result in parse_and_execute_queries("input.txt"):
    print(query_result)


Great job on writing readUntilValid as a separate function instead of inlining it in playWith. That being said, we can go a little bit further with splitting the functionality of your code.

At the moment, your main contains five distinct steps:

greet the user with the rules
choose a random number
start the game
ask whether the user wants to play again
restart

The random number is part of the game, so it's a little bit strange to generate it in main. Your function playWith already suggests a name for a another function that takes care of that step:

play :: IO ()
play = randomRIO (1, 100) >>= playWith

randomRIO takes a range, so we end up with the correct numbers. Your program choosed numbers between 0-99, by the way.

However, now we can also get the rules in there:

import Control.Monad (when)
import System.Random (randomRIO)
import Text.Read (readMaybe)

play :: IO ()
play = do
  putStrLn "I am guessing a value between 1 to 100."
  randomRIO (1, 100) >>= playWith

main :: IO ()
main = do
  play
  response <- prompt "Play again? (Y/N)"
  when (response == "Y") main

prompt :: String -> IO String
prompt xs = putStr (xs ++ " ") >> getLine

The prompt is just a little helper for questions to the user. What did we gain from splitting main? Well, main does not have to care for the game at all. We can replace play by any other game, e.g. playTicTacToe, and we don't have to change our main at all. So try to isolate your code a little bit.

Next we have playWith. There's a bug in there, you use n twice, once as (correct) answer, once as the number of turns the user has. Therefore, they have to guess 5, 4, and so on. The original random number wasn't used at all. Let's fix that first:

playWith :: Int -> IO ()
playWith answer = go 5
  where
  go 0 = putStrLn "You loose!"
  go n = do
    putStr "Enter your guess: "
    guess <- readUntilValid
    if answer == guess then
      putStrLn "You win!"
    else
      if answer < guess then
          putStrLn "Too large!" >> go (n-1)
      else
          putStrLn "Too small!" >> go (n-1)

Note that GHC will warn you about shadowing if you use -Wall. But we can still do better. If you're going to compare two values and want to act on more than a single outcome, use compare instead of two checks (here ==  and <):

playWith :: Int -> IO ()
playWith answer = go 5
  where
  go 0 = putStrLn "You lost!"
  go n = do
    putStr "Enter your guess: "
    guess <- readUntilValid

    case guess `compare` answer of
      EQ -> putStrLn "You win!"
      LT -> putStrLn "Too small!" >> go (n-1)
      GT -> putStrLn "Too large!" >> go (n-1)

And now back to readUntilValid As I said, it's completely fine, however the additional type signature isn't necessary, as the compiler can infer readMaybe's type in that context. We end up with:

readUntilValid :: IO Int
readUntilValid = do
  s <- getLine
  case readMaybe s of
    Nothing -> putStr "Please enter a valid guess:" >> readUntilValid
    Just x  -> return x

Note that you can even write it as

readUntilValid :: Read a => IO a

but that's an aside. We end up with

import Control.Monad (when)

main :: IO ()
main = do
  play
  response <- prompt "Play again? (Y/N)"
  when (response == "Y") main

play :: IO ()
play = do
  putStrLn "I am guessing a value between 1 to 100."
  randomRIO (1, 100) >>= playWith

playWith :: Int -> IO ()
playWith answer = go 5
  where
  go 0 = putStrLn "You lost!"
  go n = do
    guess <- askNumber

    case guess `compare` answer of
      EQ -> putStrLn "You win!"
      LT -> putStrLn "Too small!" >> go (n-1)
      GT -> putStrLn "Too large!" >> go (n-1)

prompt :: String -> IO String
prompt xs = putStr (xs ++ " ") >> getLine

askNumber :: IO Int
askNumber = do
  response <- prompt "Please enter your guess (1-100): "
  case readMaybe response of
    Nothing -> putStrLn "Not a valid guess, try again." >> askNumber
    Just x  -> return x

I've renamed readUntilValid and also let it ask the number, so that again everything that is concerned with getting input from the user resides in a single function.

All in all, well done. Don't be afraid to split your functions, make sure to enable compiler warnings, and use hlint (it suggested when from Control.Monad, by the way).

Exercises

at the moment, the user will only replay the game if they enter Y. Also accept other inputs, such as "yes", "YES" and "y", and ask again if they don't say "yes" or "no" in a clear way
the number of guesses is currently fixed in playWith. Make it variable
the range is currently fixed (1-100). Make it variable
have the user choose a difficulty. The difficulty should determine the original range as well as the number of guesses. Keep the lower difficulty levels fair, e.g.

 difficulty   | range      | guesses
--------------+------------+-------------------------------
 trivial      | 1-10       | 10
 easy         | 1-100      | 10
 medium       | 1-100      | 7
 hard         | 1-1000     | 10 -- still fair
 harder       | 1-10000    | 13 -- beginning to get unfair
 hardest      | 1-1000000  | 17 -- missing three guesses
 lucky        | 1-20       | 1

the user doesn't know how many guesses they have. You should probably tell them at some point, especially with difficulty levels
instead of (), playWith could return data GameEnd = Won | Lost, but that's just for style and not necessary. You could use that information for statistics and so on, but that's an overkill

Have fun.


If this is a Rails project (or you use ActiveSupport) you can replace

@old_data = old_data.reject { |k, _v| excluded_params.include? k }
with
@old_data = old_data.except(excluded_params)


Converting from decimals to roman numerals

I would define a constant overline="\u0305" and then use interpolation further down: 4 : `C${overline}D#{overline}`,, it might even make sense to define overlineD and overlineC constants. An alternative might be to create an overline method and write something like 4: overline('CD') or even a tagged template literal (4: overline`CD`) if you want to impress.
Object.keys( algarismsMap ).reverse(): The order of keys in a hash is not guaranteed, it can vary depending on the implementation and if keys have been deleted, etc. If you need order you should use an array. Also rather than reversing just define it backwards.
Rather than if {...} else [lots of code] I find it better to use an early return if {...; return; } [lots of code]
One of the biggest thing to me is the lack of tests.  I would expect to see something in an interview assignment, it doesn't have to use a framework, I would be fine with something like:

function test(number, roman) {
  if (romanizeNumber(number) !== roman)
    console.error(`Failed! ${number} should be ${roman} but was ${romanizeNumber(number)}`);
}
test(10, 'X');
test(11, 'XI');
...


if model is not None:

You do this all over the place. You should change it to:

if model:

@property is the Pythonic way to do getter and setters. For instance, I would do the following for the model variable:

Change:

self.model = model

To:

self._model = model

Create a property:

@property
def model(self):
    return self._model

@model.setter
def model(self, new_model):
    if new_model:
        self._model = new_model
    else:
        self._model = QStandardItemModel()
    self.setModel(self._model)

And do this for the other set functions.


Semantics
Put the <meta charset="UTF-8"> before anything else that is being parsed. Some sources say it must be in the first 512 characters, some sources say it must be in the first 1024 characters. To be safe, it is wise to just put it at the start. (source)
You are using inline styling. I recommend to do this via CSS.
Events
Whenever an event is fired, the this keyword is set to the current element. Your use of id in the function definition in the onblur property is thus not required. If you insist on using a closure there, you could do this instead:
(function( element ) {
   //blah
 })( this );

You can avoid using inline javascript by binding an event to an element after the DOM has loaded. See this question on StackOverflow for more details on how to figure out when the DOM has loaded.
Input validation
Your solution does not actually do input validation. This can be easily demonstrated by changing the types of your input fields to "text" and trying to submit the form. Input validation should happen on the submit event (mdn) for a form. You could still use your blur event(s) to make this process easier.


Haskell program to extract the first words of each line of a text file

Errors

The code block above is an example where your program will fail. Any empty line will lead to an empty list in words "" and therefore to head [], which calls error.

Standard library

That being said, there are some other issues with your code. You use unlines in fixLines, yet leadWords is essentially lines, although it also uses head . words internally. If we rewrite leadWords with map, we end up with

leadWords = map (head . words) . lines

which immediately shows the possible error on empty lines. Still, we can fix this if we write another function:

firstWord :: String -> Maybe String
firstWord xs = case words xs of
                   (x : _) -> Just x
                   _       -> Nothing

Now we can use mapMaybe from Data.Maybe to write leadWords:

leadWords :: String -> [String]
leadWords = mapMaybe firstWord . lines

Type signatures

Other than that, you should really add type signatures to your top-level functions. Only fixLines has one, and its not clear why that one got special handling.

Code complexity

main is overly complicated, too. We can just inline mainWidth, as its local binding doesn't yield any more comfort:

main :: IO ()
main =  do
    args <- getArgs
    case args of
        [input, output] -> interactWith fixLines input output
        _               -> putStrLn "error: exactly two arguments needed"

Alternatively, we can provide mainWith as top level function and use that in main.

Complete code

If we apply all remarks given above, we end up with something similar to the following code:

import Data.Maybe (mapMaybe)

mainWith :: (String -> String) -> IO ()
mainWith f = do
    args <- getArgs
    case args of
        [input, output] -> interactWith f input output
        _               -> putStrLn "error: exactly two arguments needed"

fixLines :: String -> String
fixLines = unlines . leadWords

main :: IO ()
main = mainWith fixLines

-- for completeness

leadWords :: String -> [String]
leadWords = mapMaybe firstWord . lines

firstWord :: String -> Maybe String
firstWord xs = case words xs of
                     (x : _) -> Just x
                     _       -> Nothing

-- That's just personal preference, your style is fine.
interactWith :: (String -> String) -> FilePath -> FilePath -> IO ()
interactWith f input output = readFile input >>= writeFile output . f

In short:

add type signatures to top-level functions
don't use head on lists that might be empty
use standard library types when possible (Maybe)
use standard library functions when possible (map, lines and mapMaybe)


Let's Break Down the Party by Breaking the Party Down Recursively

I decided to introduce a quantize() method on Denomination to do the multiplication:

public static int quantize(double input) {
    return (int) (input * MULTIPLIER);
}

This changes the Denomination's constructor:

this.centValue = quantize(value);

And the helper method itself:

public static Map<Denomination, Integer> getBreakdownRecursively(double input) {
    return recurse(Stream.of(Denomination.values()).iterator(),
            Denomination.quantize(input), new EnumMap<>(Denomination.class));
}

As hinted from above, I moved the Collections.unmodifiableMap() call to the last recursion within the recurse() method:

private static Map<Denomination, Integer> recurse(Iterator<Denomination> iterator,
        int input, Map<Denomination, Integer> result) {
    if (input == 0 || !iterator.hasNext()) {
        return Collections.unmodifiableMap(result);
    }
    Denomination current = iterator.next();
    ...
}

Now, the original approach described in the question works well and looks simple enough, but what if I went a little deeper with Java 8 features? Looks like a nice place to introduce Map.computeIfAbsent()...

private static Map<Denomination, Integer> recurse(Iterator<Denomination> iterator,
        int input, Map<Denomination, Integer> result) {
    if (input == 0 || !iterator.hasNext()) {
        return Collections.unmodifiableMap(result);
    }
    Denomination current = iterator.next();
    return recurse(iterator, result.computeIfAbsent(current, key ->
                Optional.of(Integer.valueOf(input / key.getCentValue()))
                    .filter(i -> i.intValue() != 0).orElse(null)) == null ?
                        input : input % current.getCentValue(), result);
}

Sure, readability is sacrificed, but hey, just one return statement! By taking advantage of computeIfAbsent() and its return type, I can optionally store the output of the current iteration's breakdown (when the quotient is not zero), and determine what should be the next value to recuse with (the original input, or the modulus).

edit

I suppose I can improve the readability somewhat by this...

private static Integer getValue(int input) {
    // return Optional.of(Integer.valueOf(input))
    //                 .filter(i -> i.intValue() != 0).orElse(null);
    return input == 0 ? null : Integer.valueOf(input);
}

(fixed that)

The return statement will then read:

private static Map<Denomination, Integer> recurse(Iterator<Denomination> iterator,
        int input, Map<Denomination, Integer> result) {
    if (input == 0 || !iterator.hasNext()) {
        return Collections.unmodifiableMap(result);
    }
    Denomination current = iterator.next();
    return recurse(iterator, result.computeIfAbsent(current, key ->
                getValue(input / key.getCentValue())) == null ?
                        input : input % current.getCentValue(), result);
}


You’re asking the wrong question. In reality, both methods are bad. If you need the success message, either throw an exception on failure (but only if this is really an exceptional scenario, or return the success and indicate this in the method name. For instance, by calling the method TrySomething.

In general, your example sounds like the method is actually doing two distinct things, otherwise there would be no confusion in the first place. But this is code smell anyway: every method should have only one purpose. If that is the case, then the meaning of the return value is always clear, no need to give it a name.


Convert array of arrays to array without duplicates

Adding all the elements to a Set should be generally the most efficient way. However, before you add them to the Set you are creating lots of intermediate arrays. It will likely be more efficient to just iterate over the elements and add them to the set one by one:
let set = new Set();
a.forEach(o => {
    o.items.forEach(i => {
        set.add(i.outerKey.innerKey);
    });
});
const finalArray = [...set];
console.log(finalArray);

Not sure if forEach() is the fastest way to iterate over the array elements in whatever runtime you are using. See here for a discussion of how to iterate arrays.


How can I improve CreateGenre()  function?

Remove global (this shouldn't need to be explained).

Your code depends on the class ReturnValue with method doReturn.  This is a tight coupling that makes it hard to test your code.  For your code to be reused you must also include the ReturnValue.  This is almost ok, when it is only 1 extra file, but it gets out of hand very quickly.

Your code has also become bloated by the error code handling.  Consider rewriting this with exceptions:

/**
 * Creates a genere. If one already exists it will return an error
 *
 * @param type $wpdb        Wordpress database?
 * @param type $genreName   What is this?
 * @return type
 */
function createGenre($wpdb, $genreName) {
    if (empty($genreName) || !is_string($genreName))
    {
       throw new InvalidArgumentException(
          // Choose either __METHOD__ or __FUNCTION__ depending if this is OO.
          __METHOD__ . ' genreName must be a non-empty string');
    }

    $genreName = ucwords($genreName);
    $genreSlug = text2Slug($genreName);
    $query = "SELECT COUNT (*) as count FROM `genres` WHERE `name`='" .
        $genreName . "' AND  `slug`='" . $genreSlug . "' ";
    $result = $wpdb->get_results($query);
    if ($result[0]->count > 0) {
       throw new RuntimeException(__METHOD__ . ' genre already exists.');
    }

    $formData = array(
       'name' => $genreName,
       'slug' => $genreSlug
       );

    $result = $wpdb->insert('genres', $formData);

    if (!$result) {
       throw new RuntimeException(
           __METHOD__ . ' failed to create genre: ' . $genreName);
    }
}

The code is a lot shorter and flatter (which makes it easier to test and maintain.  Arrow code is harder to debug, maintain and test - see here.

Here is the usage with exceptions:

try
{
   $genreName = 'slimy ';
   createGenre($wpdb, trim($genreName));

   return array('action'      => 'createGenre',
                'message'     => 'Genre ' . $genreName . ' has been created.',
                'returnValue' => '', // If needed even.
                'status'      => 'SUCCESS');
}
catch (Exception $e)
{
   return array('action'      => 'createGenre',
                'message'     => $e->getMessage(),
                'returnValue' => '', // If needed even.
                'status'      => 'ERROR',

}


Large-scale pairwise similarity calculations of vectors

Not so much about performance. The cosine similarity can be expressed in a more concise (and maybe even more performant) way with STL:

dot_product = std::inner_product(v1.begin(), v1.end(), v2.begin());
ss1 = std::inner_product(v1.begin(), v1.end(), v1.begin());
ss2 = std::inner_product(v2.begin(), v2.end(), v2.begin());

This of course assumes that the vectors are of the same size.
Since you want it for every pair of vectors, nothing can be done to speed thins up algorithmically. There are \$O(n^2)\$ pairs, so the performance is bound to be quadratic.
cosine_similarity works with each vector many times, and recomputes its length (ss1/ss2) many times. Compute them all in advance. It is probably the biggest performance gain you can achieve.
There is no need to pass vector_size by reference.


All in all it’s a good idea. Have you considered moving your crlf and CATCH logic; or a portion of it; to a reusable function? This would help ensure; wherever it’s used; that it remain consistent and you don’t have the same code all over the place.


eval is evil

Always look for ways to avoid eval.

Relevant snippet from the posted code:

curl -snL  "$url?pagelen=0&page=1" \
    | jq '"$(((\(.size) / 50) + 1 ))"' \
    | xargs bash -c 'eval "echo $1"' _

The code uses jq to create a formatted expression to evaluate by Bash,
with .size injected in the middle of the expression.

A better way to achieve the same thing would be to make jq simply output the variable itself, and then write the expression in Bash:

curl -snL  "$url?pagelen=0&page=1" \
    | jq -r .size \
    | xargs bash -c 'echo $((($1 / 50) + 1))' _

Unnecessary pipeline

It's strange to use xargs to process one line of input,
and it's strange to spawn another Bash just to evaluate an expression.
There's really no need to force a chain of operations in a single pipeline.

I'd rewrite the above snippet like this:

repos_count=$(curl -snL "$url?pagelen=0&page=1" | jq -r .size)
((pages_count = (repos_count / 50) + 1))

Store positional arguments in variables with descriptive names

It's a mental burden to have to remember what $1 and $2 mean.
I'd store them in local variables with descriptive names at the beginning of the function.

Avoid seq

Is it obsolete, and not available in all systems.
Use a Bash counting loop instead:

for ((page = 1; page <= pages_count; page++)); do
    ...
done \
| xargs -L 1 ...

Break lines in long pipelines

It's easier to read code when there's one statement per line.
This is especially true when a line is so long you have to scroll to the right to see it.
So instead of this:

| xargs bash -c 'eval "echo $1"' _ | xargs seq 1 | xargs -L 1 printf "?pagelen=50&page=%s&${1:-$project}\n" \
| xargs -I {} -L 1 -P 20 -I {} bash -c 'curl -snL  "$1/$2" | jq -er .values[].links.clone[1].href' _ $url {} \ #clone[1] is ssh
| sort -u

I recommend to write like this:

| xargs bash -c 'eval "echo $1"' _ \
| xargs seq 1 \
| xargs -L 1 printf "?pagelen=50&page=%s&${1:-$project}\n" \
| xargs -I {} -L 1 -P 20 -I {} bash -c 'curl -snL  "$1/$2" \
| jq -er .values[].links.clone[1].href' _ $url {} \
| sort -u

Always double-quote variables used as command line arguments

In | jq -er .values[].links.clone[1].href' _ $url {}
you forgot to double-quote $url.


CareerCup (Bloomberg): Check if string is valid based on brackets

Guard conditions

ArgumentNullException is typically thrown on incorrect usage of the API. It is not an end-user exception, so I would not bother with an exception message.

  throw new ArgumentNullException("A string is required");

throw new ArgumentNullException(nameof(s)); // perhaps rename 's' to 'input' or 'value'

For the ArgumentException instances you throw, I would also add the nameof(parameterName) to the constructor. A decent error message is relevant here, so keep the message.

You have a guard on whitespace. I don't see this in the spec. Is this a requirement? If not, allow white space as either an open or close bracket.

  if (char.IsWhiteSpace(open) || char.IsWhiteSpace(close))

The next guard checks on duplicate registrations. An alternative policy is to ignore a registration if already registered. This depends on whether you want your API to be error-prone or act as a sandbox for consumers.

  if (openBrackets.Contains(open) || openBrackets.Contains(close))

I'm missing a guard condition. I doubt open and close can be the same.

if (open == close)  // throw ..

Readability

You could substitute some if statements with a ternary operator.

s = s ?? throw new ArgumentNullException(nameof(s));
validator = validator ?? BracketValidator.CreateDefaultValidator();

Redundant type declarations can be replaced by var. Unlike javascript, var is ok in C#.

  Stack<char> openStack = new Stack<char>();

var openStack = new Stack<char>();


Bash script to extract HTML comment into a Markdown file

A bug

If your html contains a backspace character e.g

The special character \n is a way to include read line

your code interprets it a

  The special character n is a way to include read line.

to avoid this, add "-r" switch to your read line

cat  hot-form-validator.html | while  read -r "line";do

You want to check if your file exists before reading it

if [ -f $filename ]; then
#do something
else
#do something
fi


Check string value of boolean to a mapped enum

The redundant logical expression seems to be too complex for this case.

And there is probably a bug. You say that the expected set of values for it is ("0", "1", "false", "true"), but if value = "2", it will also evaluate to "true":

!("0".equals("2") || "FALSE".equalsIgnoreCase("2")); ->

!(false || false) -> !false -> true

"2" is weird for "true" value.

So I suggest to reformulate the expression to

Boolean.parseBoolean(value) || "1".equals(value)

"1" is still there, because parseBoolean checks for equivalence for "true" string value.

The logic of the entire method can be thus reformulated with improved readability and simplified:

public boolean createParameterObjectValue2(String value) {
  return Boolean.parseBoolean(value) ||
         "1".equals(value) ||
         evaluatesToTrueFromMetadata(value);
}

private boolean evaluatesToTrueFromMetadata(String value) {
  return getMetaData().getValidValues().isAvailable() &&
      getMetaData().getValidValues().getType() == ValidValues.Type.ENUM &&
      getMetaData().getValidValues(EnumValidValues.class).getEnumName(1).equalsIgnoreCase(value);
}

getMetaData().getValidValues() in the private method should also be extracted to a local reference in order to shorten the expression.


You could simplify the yes/no answer checks:

if answer.lower() in ('y', 'yes'):
    # ...

And instead of writing these repeatedly, you could create a helper function to encapsulate this logic:

def is_answer_yes(answer):
    return answer.lower() in ('y', 'yes')


OOP and non-OOP versions of layout and page animation code

I think you are over-engineering here. OOP is not an end in itself, so don't convert your code to "OOP style" just because.

The most desirable property of code (after correctness) is clarity. Clarity means obviousness, which means ease of maintenance, both of which mean reduced chance of bugs. To me, your second code sample is less clear than your first.

I would go into a different direction and just try to simplify your first code sample instead of slapping some fancy "OOP" stuff on.

Part of simplification is abstracting functionality into re-usable blocks. jQuery is very easy to extend with your own functions, so let's create two extensions maxHeight and positionCenter:

$.fn.extend({
    maxHeight: function () {
        var heights = this.map(function() { return $(this).height(); });
        return Math.max.apply(null, heights);
    },
    positionCenter: function () {
        return this.each(function () {
            var $this = $(this),
                height = $this.outerHeight(true),
                width = $this.outerWidth(true),
                browser_height = $(window).height(),
                top = 10,
                page_pos = document.documentElement.scrollTop || document.body.scrollTop;

            if (height < browser_height) {
                top = browser_height / 2 - height / 2;
            }
            $this.css({
              top: page_pos + top
              // "left" calculation is still missing
            });
        });
    }
});

This could end up in a script file where you collect all your custom extensions.

With some of the plumbing out of the way, the code that actually works on the page becomes a whole lot clearer:

$(window).scroll(function () {
    var $window = $(window);
    $('.fade-me').each(function() {
        var $this = $(this);
        if ($window.scrollTop() > $this.offset().top - $window.height() / 1) {
            $this.addClass('is-showing');
            // when is this class removed?
        }
    });
});

$(function () {
    $('.equal').each(function() {
        var $sections = $(this).children().height('auto');
        $sections.height( $sections.maxHeight() );
    });
    $('.popup').positionCenter();
});

(The above is of course untested, you might have to tweak it a little here and there.)

The next thing you could investigate is making your own custom jQuery selectors.

Imagine your code scroll handler would look like this:

$(window).scroll(function () {
    $('.fade-me:inview').addClass('is-showing');
});

Wouldn't that be even clearer?

Here is how to do that: http://www.sitepoint.com/make-your-own-custom-jquery-selector/

As a finger exercise, write a jQuery extension named equalizeHeight, such that you can make the following simplification:

$('.equal').each(function() {
    $(this).children().equalizeHeight();
});


You are using int64_t, so most of your code gets compiled into the same machine code regardless of the bitness of the target. Also, A^A = 0, so the compiler might be optimizing your entire for loop with a single call to memset with zero.

I would recommend that you move different values around instead of xoring the same values together, and I would recommend that you use int32_t for the 32-bit version, and int64_t for the 64-bit version.


How would I make this bubble sort more pythonic?

One approach is to move most of the logic into a helper function that does the
swapping and returns the N of swaps. The outer part of the algorithm then
reduces to almost nothing.
While you're at it: (1) use conventional names for Python variables (lowercase
for variables, capitalized for classes, uppercase for constants); (2) let your
operators breathe for readability, (3) take full advantage of enumerate(),
which gives both index and value (x1), (4) use convenience variables to make
code more readable (x2 rather that repeated uses of xs[i + 1]); (5)
look for ways to pick simple variable names that help the reader understand the
algorithm (i for an index; xs for a list of values; x1 and x2 for
individual values that are being swapped) rather than purely abstract variable
names that convey nothing substantive to the reader (List, x for an
index, and y for a value); and (6) put your sort in a proper function.
def bubble_sort(xs):
    while bubble(xs):
        pass

def bubble(xs):
    n_swaps = 0
    for i, x1 in enumerate(xs[:-1]):
        x2 = xs[i + 1]
        if x1 > x2:
            xs[i] , xs[i + 1] = x2, x1
            n_swaps += 1
    return n_swaps

vals = [9, 3, 4, 2, 6, 8, 10, 1]
bubble_sort(vals)
print(vals)


Handling exceptions from async call in synchronous caller

You're correct that you don't need Wait to inspect the Exception of a completed Task.  You can use the Exception property to look at the exception.  You can also use the only on faulted continuation option if you only want to perform the action if the task faults.  This lets you turn the continuation into:

ProcessCommand()
    .ContinueWith(t => ShowMessage(t.Exception.Message),
        TaskContinuationOptions.OnlyOnFaulted);

Next, you handle the case where ProcessCommand throws, rather than returning a faulted Task.  If at all possible, I'd avoid the situation entirely.  If it's your own method, redesign it such that it only ever returns a faulted task if there's an exceptional problem, rather than throwing, rather than handling both cases any time you ever want to add a continuation to any asynchronous operation.  If you're calling method you don't control, like an API that's constructed to both throw and return faulted tasks, then yes, you do need to handle both, but this should be rare.  If you're writing code like this often, then you're probably doing something wrong.  If it is something you find yourself doing a lot, then at a minimum write a method that does the boilerplate, rather than repeating it:

public static Task WrapExceptions(Func<Task> asyncFunction)
{
    try
    {
        return asyncFunction();
    }
    catch (Exception e)
    {
        return Task.FromException(e);
    }
}
public static Task<T> WrapExceptions<T>(Func<Task<T>> asyncFunction)
{
    try
    {
        return asyncFunction();
    }
    catch (Exception e)
    {
        return Task.FromException<T>(e);
    }
}

Now you can write WrapExceptions(ProcessCommand) (If ProcessCommand cannot be refactored itself) and have a method that never throws, and only ever returns a faulted task in exceptional situations.


Configure AspNet.Identity to allow for either username OR email address on login

I added some formatting to that nested ternery to try to understand what it's doing, and it still took me a while!

model.Username = (db.Users.Any(p => p.UserName == model.Username))
    ? model.Username
    : (db.Users.Any(p => p.Email == model.Username))
        ? db.Users.SingleOrDefault(p => p.Email == model.Username).UserName
        : model.Username;

It seems to have 3 possible paths, and only one of them actually does anything (since the other two just set model.Username to model.Username).

So it looks like this is actually trying to say:

if(!db.Users.Any(p => p.UserName == model.Username)
    && db.Users.Any(p => p.Email == model.Username))
{
    model.Username = db.Users.Single(p => p.Email == model.Username).UserName;
}

(Not that I've changed SingleOrDefault to Single. This practically shouldn't have an effect but is a slightly more appropriate method for the situation)

Okay, that's a little better, and we could extract the conditional to its own method for readability. But it's still problematic:

It's making 3 database calls (via EF) to get one piece of information
It's having to use some pretty roundabout logic to do this. For example, it relies on the fact that no valid email address could also be a valid username. This is domain logic, which shouldn't be encoded (or repeated) here.

The first point could be improved on with some further rejigging:

var user = db.Users.Where(p => p.UserName == model.Username || p.Email = model.Username)
    .SingleOrDefault();
if(user != null)
{
    model.Username = user.UserName.
}

Here we're relying on:

Uniqueness of usernames
Uniqueness of email addresses
No string can be valid as both a username and email address

Of those, only the first one is a new assumption compared to the original code

The second point is rather more difficult to deal with. While it would be possible to move the logic for matching against an individual username or email to a User class, it would be hard to do that in a way which EF would still be able to translate to SQL. To avoid adding a lot of complexity, it's probably best not to try to do this. Do make sure your validation won't allow for usernames and email addresses which could match, though!


Determining primality by removing select composits

You should use more Data.List functions - explicit recursion is hard to read.

comp1 y = sort [ m
  | (i,n) <- zip [0..149] n7sl
  , m <- takeWhile ((<= 11 * last (take y n7sl))) $ map (n*) $ drop i $ take n n7sl
  ]

Edit: Not sure whether my version fails to be equal to your original one, but here's a further refactoring of the one in your comment to get rid of some number manipulation. The takeWhile reflects the short-circuiting behavior of the original, explicitly recursive implementation, which uses that bs is ascending.

t = sort [ m | bs@(a:_) <- tails n7s,
  m <- takeWhile (<= 11*last n7s) $ map (a*) bs]


It looks like you don't really need to exit out of the PHP tag on this one.

<?php
    $akhbarkotah1 = $conn->prepare("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
    $akhbarkotah1->execute();
    while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)){
        echo "
" . $obj->text . "
";
    }
?>

This simplifies the code and shortens it.  I think that I have the Syntax Correct.  I am rather new to PHP myself but I am pretty sure that this will work exactly the same.

If you leave your code the other way you should indent the HTML to match what is inside the PHP since it is really inside the PHP (kind of/sort of)  like this

<?php
    $akhbarkotah1 = $conn->prepare("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
    $akhbarkotah1->execute();
    while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)){
?>

<?php echo $obj->text; ?>

<?php
    }
?>

I personally don't like the way that this looks though.


You don't need to declare password to just use on the next line and never again. Use the literal directly:

self.key = hashlib.sha256('password').digest()

You have some confusing names, like s and iv. Renaming these to be more explicit, like string for s would make it more readable. As would adding docstrings or (less preferably) comments to explain the context of what each function is exactly. At the very least your overall class should have a docstring for a user to know about the general practice of the class.