Count the number of combinations with gap-restriction for every pair of values

There's no docstring. How do I use this function? What arguments do I pass? What does it return?
It would be very easy to make this code portable to Python 3: just put parentheses around the argument to print.
There's no need to terminate a statement with a semicolon in Python.
The name func does not give any hint as to what the function might do. A name like combinations_with_gap would be clearer.
When you have code that accumulates a sum like this:

count = 0
for n in A:
    count += B

you can use the built-in sum:

count = sum(B for n in A)

If you're just counting combinations (rather than generating the combinations themselves), then you don't need the array variable, just its length.
Presumably the caller is supposed to always pass the empty list [] for array and 1 for min. In that case, why make them do it? It would be easier for the caller if the function just took the arguments you need, and used a local function to do the work, like this:

def combinations_with_gap(k, max, gap):
    """Return the number of ways of choosing k of the numbers from 1 to
    max such that no two numbers are closer than gap.

    """
    def c(length, min):
        if length == k:
            return 1
        return sum(c(length + 1, n + gap) for n in range(min, max + 1))
    return c(0, 1)

This runs in just over 4 seconds on my computer:

>>> from timeit import timeit
>>> timeit(lambda:combinations_with_gap(6, 50, 3), number=1)
4.182408502034377

Where is it spending its time? If you trace the calls to the inner function c, you'll see that the same values for length and min occur many times. This is a waste of effort: having computed c(5, 44), say, it would be a good idea to remember the result and reuse it instead of computing it again.

One way to do this is to memoize the function, for example using the @functools.lru_cache decorator:

from functools import lru_cache

def combinations_with_gap(k, max, gap):
    """Return the number of ways of choosing k of the numbers from 1 to
    max such that no two numbers are closer than gap.

    """
    @lru_cache(maxsize=None)
    def c(length, min):
        if length == k:
            return 1
        return sum(c(length + 1, n + gap) for n in range(min, max + 1))
    return c(0, 1)

This version takes just a couple of milliseconds:

>>> timeit(lambda:combinations_with_gap(6, 50, 3), number=1)
0.0017554410151205957


Switch questions using JavaScript and CSS

JavaScript

I would make the following changes in the jQuery code:
1) Create a private scope for your code using an IIFE.
2) Cache your selectors.
3) Supply the "radix" parameter to parseInt.

(function( $ ) { //start IIFE to create a private scope and $=jQuery

  function updateElement() {
    var $this = $(e.currentTarget),  //cache selectors
        $parent = $this.parent(),
        wid = 0, margin = 0;
    wid = parseInt( $parent.css('width'), 10); //added radix parameter
    margin = parseInt( $parent.css('marginLeft'), 10);
    $parent.css('marginLeft', (margin - wid) + "px");
  }

  $(function(){
    $("#parent").on( 'click', '.children', updateElement );
  });

})( jQuery );  //pass jQuery to function so $ is always set correctly.

If you are pointing to the #parent element you could change the JS to be more performant by caching the parent element as well.

 (function( $ ) {

  var $parent = $('#parent');

  function updateElement() {
    var wid = 0, margin = 0;
    wid = parseInt( $parent.css('width'), 10); //added radix parameter
    margin = parseInt( $parent.css('marginLeft'), 10);
    $parent.css('marginLeft', (margin - wid)+ "px");
  }

  $(function(){
    $parent.on( 'click', '.children', updateElement );
  });

 })(jQuery);

CSS

In your CSS you should remove the vendor prefixes or supply all of them ( Here is a list. Ok not all just the most common: ms,o,moz,webkit,etc ). Also, you should include the non-prefixed property last in the list so that once it is available non-prefixed your code still works.

#parent {
  -moz-transition: all .2s linear;
  -o-transition: all .2s linear;
  -ms-transition: all .2s linear;
  -webkit-transition: all .2s linear;
  transition: all .2s linear;
}

You could also use a tool like autoprefixer in your build process to add the prefixes automatically.  I would recommend this approach.


Printing odd and even numbers with two threads

Inconsistency
In OddNumberGenerator your printer is called q.  In EvenNumberGenerator it is called printer.  Why the difference?
The odd one prints to max-1 but the even one prints to max.  They should both print to max, otherwise you are assuming that max must be even.
No check after wait
After your wait() call, you don't check to see if you are in the correct state before printing the next number.  If both threads called printOdd(), it would happily print two or more odd numbers in a row.  It's not a problem with your program because your two threads are well behaved, but it isn't a very good example of using synchronization.
Simplification
You don't need separate printOdd() and printEven() functions that do almost the same thing.  You could combine them into a single printNumber() function.
Similarly, you don't need two number generators.  If you just added a start variable to the number generator, you could create an odd generator with a start value of 1 and an even generator with a start value of 2.


The logic isn't so easy to follow, especially since the loops in copy
and checksetup imply that there are more lines, but really there will
be only two at most, the bookmark and backup folder.  I'd suggest making
that more obvious and avoiding for line in file: in case you only ever
want to have a fixed number of lines in that file.

The code also doesn't work with no "user.txt" file present, so some
more checks and error handling are necessary to handle that case as
well.

Some of the paths and other constructs are duplicated, I'd always try to
minimise the amount of duplication, so with that in mind, consider more
constants and variables to extract common code.

The .seek(0) in checksetup isn't necessary with mode 'r'; if you
open a file (for reading) you'll already be at the start; however, the
mode should probably be 'a+' anyway to create the file if it doesn't
exist.
If you don't like the escapes all the time, consider using the r""
syntax instead.
Use the if __name__ == "__main__": ... construct as is customary,
that way this file could be imported and used without running
checksetup as is it would currently.
Python typically uses lower case names with underscores between words,
c.f. PEP8.
For the date formatting use the strftime method instead to get the
desired output directly.
The setup method could use some more error checks, e.g. whether the
folders exist.
The "user.txt" file is opened three times in the worst case; it
would also be better to pass the two values necessary for the script
in the script as function arguments instead of parsing the file so
often; I'll leave that be for the moment though.  In general I'd say
that copy should have the signature
copy(bookmark_directory, backup_directory) and should be called with
the values from the file instead of parsing it.

After all that you can also look into command line arguments using
e.g. argparse for
parsing options, that way users won't have to deal with pesky manual
input instead of reusing the shell completion (for specifying the
folders).

So, it should look more like this perhaps:

import shutil
import os
import datetime

SETUP_FILE = 'user.txt'

def setup():
    print ('Enter your Chrome bookmark directory.')
    print (r'Standard one is: C:\Users\<USER>\AppData\Local\Google\Chrome\User Data\Default')
    bookmarkfolder = input('> ')

    print ('Enter the folder you want to save the backup files in.')
    print (r'For example: C:\Users\<USER>\Desktop\Chrome Bookmarks')
    backupfolder = input('> ')

    with open(SETUP_FILE, 'w') as txt:
        txt.write(bookmarkfolder + '\n' + backupfolder + '\n')

    copy()

def copy():
    with open(SETUP_FILE, 'r') as txt:
        user_list = [line.strip() for line in txt]

    shutil.copy(user_list[0] + r'\Bookmarks', user_list[1])

    new_name = datetime.date.today().strftime('Bookmarks%Y%m%d')
    try:
        os.rename('Bookmarks', new_name)
    except WindowsError:
        os.remove(new_name)
        os.rename('Bookmarks', new_name)

def checksetup():
    try:
        with open(SETUP_FILE, 'r') as txt:
            txt.seek(0)
            line = txt.readline()

        if '\\' in line:
            copy()
        else:
            setup()
    except FileNotFoundError:
        setup()

if __name__ == "__main__":
    checksetup()


Python3: using generator to process a very large list of integers

I would guess the biggest slowdowns are the append and list functions. In your second example, you attempt to pre-create a list, which is a good idea, but a) you use the wrong size, and b) you never use the created list. Here's an example using a pre-made list:
def xor_subqueries(array, queries):
    result = [0] * len(queries)
    for i,q in enumerate(queries):
        val = array[q[0]]
        for j in range(q[0]+1, q[1]+1):
            val ^= array[j]
        result[i] = val
    return result

Pretty straight forward. I'm not so sure this task calls for a generator function, but here's an example of using one:
def xor_subqueries(array, queries):
    def genx():
        for q in queries:
            val = array[q[0]]
            for j in range(q[0]+1, q[1]+1):
                val ^= array[j]
            yield val

    result = [0] * len(queries)
    for i,q in enumerate(genx()):
        result[i] = q
    return result

However, I have read that list comprehension is faster. You could easily re-write the above function using list comprehension (return [x for x in genx()]), but here is an example using the built-in functions reduce and xor which stand-in for your generator function.
from functools import reduce
from operator import xor

def xor_subqueries(array, queries):
    return [reduce(xor, array[q[0]:q[1]+1], 0) for q in queries]

It calls reduce on the sub-list array[q[0]:q[1]+1]). reduce calls xor on each element of the sub-list with the previously calculated value and an initial value of 0.


If you are just trying to make an interactive calculator, the classes, etc. are not needed.
First, make a simple table that lets you look up the stats based on race. Keep it easy for a human (like you) to edit it, make changes, add new races or stats, etc.
keys = "base_strength base_agility base_health strength_cost agility_cost health_cost".split()

traits = [
    #        base     base    base  strength agility health
    #race  strength agility  health   cost     cost   cost
    "human    15       17      18      5        3      4",
    "elf      11       21      14      4        3      5",
    "giant    25       11      27      4        8      3",
]

It's just a list of strings. Now transform it into a format that makes it easy to use in a program.  We'll turn it into a dict of dicts so we can look up values using something like: stat["elf"]["base_agility"].  Here's the code:
stats = {}

for row in traits:
    row = row.strip().split()
    stats[row[0]] = dict(zip(keys, map(int, row[1:])))

Now your code that calculates the cost of changing strength for a human, can be turned into a generic function that works for any race or stat:
def calc_change_cost(race, stat_name, present_value, desired_value):
    base_value = stats[race][f"base_{stat_name}"]
    stat_cost = stats[race][f"{stat_name}_cost"]

    present_statdif = present_value - base_value
    present_stat_cost = stat_cost + (present_statdif - 1) * stat_cost
    total_present_cost = (present_statdif / 2) * (stat_cost + present_stat_cost)

    desired_statdif = desired_value - base_value
    desired_stat_cost = stat_cost + (desired_statdif - 1) * stat_cost
    total_desired_cost = (desired_statdif / 2) * (stat_cost + desired_stat_cost)

    net_cost = total_desired_cost - total_present_cost

    return net_cost

You'll notice the repeated code for calculating total_present_cost and total_desired_cost.  Those lines could be refactored into another function (an exercise for the reader).
Now, the main program just collects the user's inputs, calls the function above, and prints the results:
user_race = str(input("Enter your race (Human, Giant, Elf):")).lower()
user_stat = str(input("Enter your desired stat (Strength, Agility, Health):")).lower()
present_value = int(input("Enter your present stat value:"))
desired_value = int(input("Enter your desired stat value:"))

net_cost = calc_change_cost(user_race, user_stat, present_value, desired_value)
print(f"Net cost to change {user_race} {user_stat} from {present_value} to {desired_value}: {net_cost}")


Calling different bundles in parallel using ExecutorService

I need to call all those 5 Bundles process method in parallel using
  multithreaded code and then write to the database. I am not sure what
  is the right way to do that? Should I have five thread? One thread for
  each bundle? But what will happen in that scenario, suppose if I have
  50 bundles, then I will have 50 threads?

It is recommended not to have more threads than the number of physical cpu's on that machine in order to be efficient. So if you have 50 Bundles and 8 cores for instances than an ExecutorService with 8 threads should be enough. The bundles will be executed 8 at a time and at most there will be 50/8 rounds of execution. (In real world some of the bundles will execute faster, etc.)

  And also, I want to have timeout feature as well. If any bundles is
  taking lot of time than the threshold setup by us, then it should get
  timeout and log as an error that this bundle has taken lot of time.

You could use a Timer (ScheduledExecutor) on which you register the action to take place in case of a timeout.
On timeout you should iterate the list of futures and cancel the ones that are not done yet.

Otherwise the code looks good enough. I can't see why should not be optimal.


Creating a thumbnail of a PDF using Cairo, Poppler and Rust

This seems pretty good to me. I didn't notice any bugs, and I don't have knowledge of what pdf crates are available, so I just have a few points about idiomatic Rust.

To start, I just want to note that when I tried to create this project locally to work on, I had to fiddle around with the versions of the crates to get a working combination, which makes it an especially good idea to include what versions you're using somewhere in your question.

You can simply remove all uses of extern crate some_crate, since they aren't needed anymore in rust 2018 edition (the default by now).

I like the use of an error enum. You could consider using something like the crate thiserror to derive Display and From instances for the enum. (This just reduces boilerplate.)

I often like having type Result<T, E = MyErrorType> = std::result::Result<T, E>;, especially for a library, which lets me write Result<()> to use my error or Result<(), OtherError> to use another.

pub fn create_thumbnail(pdf_path: &Path, out_path: &Path) -> Result<()> {
    let doc = PopplerDocument::new_from_file(pdf_path, "")?;

    let page = doc.get_page(0).ok_or(Error::NoPagesError)?;

    let (width, height) = page.get_size();

    let surface = ImageSurface::create(Format::Rgb24, width as i32, height as i32)?;

    let ctxt = Context::new(&surface);
    ctxt.set_source_rgb(1.0, 1.0, 1.0);
    ctxt.paint();

    page.render(&ctxt);

    let mut f = File::create(out_path)?;
    surface.write_to_png(&mut f)?;

    Ok(())
}

You should use Paths when you're representing paths. You can use ok_or or ok_or_else to convert Option to Result, which works well with ?. Rust can infer the type of your floats in set_source_rgb, but if you want to be explicit then you should use 1.0f64 rather than 1.0 as f64. I removed your comments just for space in the answer, but they are meaningful since they give reason and don't just restate the code.


Modeling Cash-Case differences - should WebAPI DTO's be flat?

My vote is for not-flat, for several reasons:

The names of the members are less redundant, both in code and over the web
Code is more easily testable. If ever there is a method that deals only with the "difference" fields, there's less surface area to deal with than if you had to manipulate an entire CashCase.
Cardinality. If ever there comes a time that you need to remodel the application to support more than one "difference", having a CashCaseDifference class makes that effort trivial.


Ruby: refactor simple string method for aligning DSV text

Some notes:

include DreftymacAddon::String. Monkeypatching common classes is always controversial, but in this case I wouldn't do it, it's not a general enough abstraction.
As always, I'd recommend using functional style with Ruby (if you check my other answers in this site, it's all I do ;-)) unless you have a very good reason not to. No sout = "", asize = [], each, array[key] = value, += and other statements, use expressions.
dsvpretty(delim=';;',padd=''). This kind of signature is problematic, if you want to set padd you are forced to set also delim when you wanted to keep the default value. Use an options hash instead. Note that finally Ruby 2.0 provides keyword arguments.
each_with_index{|currfld,icc|. Let the block breathe, and don't forget spaces after commas: each_with_index { |currfld, icc|. More on idiomatic Ruby.

I'd write:

module DreftymacAddon
  def self.dsv_pretty(string, options = {})
    options = {:delim => ";", :padding => ""}.merge(options)
    rows = string.strip.split(/\n/).map { |line| line.strip.split(options[:delim]) }
    columns_max_width = rows.map { |row| row.map(&:size) }.transpose.map(&:max)
    columns_separator = options[:padding] + options[:delim] + options[:padding]

    rows.map do |row|
      row.zip(columns_max_width).map do |cell, column_max_width|
        cell.ljust(column_max_width)
      end.join(columns_separator)
    end.join("\n")
  end
end

puts DreftymacAddon::dsv_pretty(vout, :delim => '|', :padding => " ")


Changing attributes in Django Objects outside of iteration

Right now you are iterating over the queryset three times in order to get set the immediate_parent and later set is_parent. While it doesn't look like you can cut this down to a single iteration, you can definitely cut it down to two.

Removing the extra iteration

Right now you are iterating over your queryset three times

Set the immediate_parent on the object
Get a list of all of the parents
Set is_parent on the object

Which works, but you can actually combine the first two iterations into a single one. This is because getting the list of the parents does not require any extra knowledge that comes after the first iteration. So you end up with

Set immediate_parent and build a list of parent ids
Set is_parent on the object if it's a parent

Or in code form

causelist_data = CauseHierarchy.objects.filter(cause_set_version_id=cause_set_version_id).extra(order_by=['sort_order']).prefetch_related('cause_id','parent_id')
parents = []

for c in causelist_data:
    c.display_name = c.cause_id.cause_name + " (" + c.cause_id.acause + ")"
    if len(c.path_to_top_parent.split(',')) == 1:
        c.immediate_parent = c.path_to_top_parent.split(',')[-1]
    else:
        c.immediate_parent = c.path_to_top_parent.split(',')[-2]
    parents.append(int(c.immediate_parent))

for c in causelist_data:
    if int(c.cause_id_id) in parents:
        c.is_parent = True

Use sets where the list can only have unique values

Right now you are using a list for parents, so each time you append the parent, it gets added to the list. This means that there can be multiple ids in the list for a single parent, which doesn't make sense when we are just using it to check for the existence of the id.

You can use a set instead. This has the benefit of having a faster lookup time, so the second iteration won't take as long.

parents = set()

for c in causelist_data:
    parents.add(int(c.immediate_parent))

Use in to check if a character is in a string

Right now in your first iteration you are looking for a , in the path_to_top_parent in order to determine if there is only a single parent in the path of now. But you're doing this by splitting the string on , and checking that there is only one part (so there wasn't a ,).

if ',' in c.path_to_top_parent:

Is the same as

if len(c.path_to_top_parent.split(',')) > 1:

But it has the added benefit of making it clear why you are branching there.

Putting it all together

causelist_data = CauseHierarchy.objects.filter(cause_set_version_id=cause_set_version_id).extra(order_by=['sort_order']).prefetch_related('cause_id','parent_id')
parents = set()

for cause in causelist_data:
    cause.display_name = cause.cause_id.cause_name + " (" + cause.cause_id.acause + ")"

    if ',' in cause.path_to_top_parent:
        cause.immediate_parent = cause.path_to_top_parent.split(',')[-2]
    else:
        cause.immediate_parent = cause.path_to_top_parent.split(',')[-1]

    parents.add(int(cause.immediate_parent))

for cause in causelist_data:
    if int(cause.cause_id_id) in parents:
        cause.is_parent = True


Using a recurring System.Threading.Timer in an Mvc Application

Looks mostly ok, just some issues around coupling:

Consider one of the following

Pass MessageBroker.Publisher via the ApplicationClock constructor as an external dependency (preferably an interface). This will make the current implicit dependency explicit and visible which should yield in better maintenance in the future and easier unit testing.
Pass the tick handler in as an Action parameter - no dependency on a specific object at all.
Expose a ClockTick event and raise the event handler on tick. This way anyone interested in the clock can subscribe and the clock doesn't need to know about them at all.

Also your tick interval is hard coded, it should be passed in as parameter.


Parsing JSON and exploring relationships in Python

Writing pythonic code

Python has a coding guideline called PEP 8. It contains a lot of relevant information about how to write your code. You'll find various tools to check your code againt PEP 8 to ensure you follow it properly.

Among other things :

  For sequences, (strings, lists, tuples), use the fact that empty
  sequences are false.

In your case, you should write while to_explore instead of while to_explore != [].

A bit of scafolding

In order to improve your code, it is a good thing to split it into different parts. Here I have splitted your code into functions. I took this chance to move the part calling functions behind an if main guard. Also, I have hardcoded some values to make testing easier. To make things better, the different functions should be documented but I can't be bothered.

import json

def get_input_data(from_user = False):
    if from_user:
        # standardize all input names to lower case
        user1 = raw_input().lower()
        user2 = raw_input().lower()
        with open(raw_input()) as f:
            json_data = json.load(f) # JSON representation of input file
    else:
        user1 = 'user1'
        user2 = 'user2'
        json_data = json.loads('{ "TweetCount" : 1, "TwitterData" : [ { "userName" : "user1", "tweetid" : 12345, "tweet" : "@user2" } ] }')
    data = json_data['TwitterData']
    return (user1, user2, data)

def chain_exists(user1, user2, data):
    user1_mentions = []
    to_explore = []
    reached = [] # list of users reached

    # find user1's mentions
    for tweet in data:
        if tweet['userName'] == user1:
            user1_mentions += ([x[1:].encode('utf-8') for x in tweet['tweet'].split() if x.startswith('@') and x[1:].isalnum()])
            to_explore = user1_mentions

    while to_explore != []:
        temp_to_explore = [] # temp array for storing words to explore next
        for tweet in data:
            if tweet['userName'] in to_explore:
                temp_to_explore += ([x[1:].encode('utf-8') for x in tweet['tweet'].split() if x.startswith('@') and x[1:].isalnum()])
        reached += to_explore
        to_explore = temp_to_explore

    print reached # ['user2', 'user4']
    return user2 in reached

if __name__ == '__main__':
    user1, user2, data = get_input_data()
    print(chain_exists(user1, user2, data))

It could be interesting to add more hardcoded tests.

A bit of logic

Everytime you add something to user1_mentions, you change to_explore. It probably would make sense to get the value at the end of the loop.

# find user1's mentions
for tweet in data:
    if tweet['userName'] == user1:
        user1_mentions += ([x[1:].encode('utf-8') for x in tweet['tweet'].split() if x.startswith('@') and x[1:].isalnum()])
to_explore = user1_mentions # this doesn't need to be defined before this point

The right data structure

The way you build user1_mentions, it might contain the same value multiple times. It is something we might want to avoid because it will not bring anything except performance issues. Instead of using list, you should use sets.

def chain_exists(user1, user2, data):
    user1_mentions = set()
    reached = [] # list of users reached

    # find user1's mentions
    for tweet in data:
        if tweet['userName'] == user1:
            user1_mentions.update([x[1:].encode('utf-8') for x in tweet['tweet'].split() if x.startswith('@') and x[1:].isalnum()])
    to_explore = user1_mentions

    while to_explore:
        temp_to_explore = set() # temp set for storing words to explore next
        for tweet in data:
            if tweet['userName'] in to_explore:
                temp_to_explore.update([x[1:].encode('utf-8') for x in tweet['tweet'].split() if x.startswith('@') and x[1:].isalnum()])
        reached += to_explore
        to_explore = temp_to_explore

    print reached # ['user2', 'user4']
    return user2 in reached

The very right data structure

In order to use to implement efficient algorithm, you'll need to preprocess your data into something relevant. Mapping user names to the set of users they mention is likely to be required. Here's a piece of code to do so :

def make_graph_from_data(data):
    graph = {}
    for tweet in data:
        graph.setdefault(
            tweet['userName'],
            set()).update(x[1:] for x in tweet['tweet'].split() if x.startswith('@') and x[1:].isalnum)
    return graph

Once you have the data preprocess, you won't need to worry about parsing tweets or whatever.

A simple bug

What if a user was to mention hisself ? You'd get stuck in the loop.

Conclusion

You'll find various solutions to your problem in the litterature so I'll let you have a look at this : it might be a good idea to consider solutions to the shortest path problem by considering a graph : you are in a case of Directed graphs with nonnegative weights. There might be some even more relevant algorithm because you care about the existence of a chain but not so much about it length but I don't have a particular algorithm in mind.


Prime generator SPOJ problem in Python 3

I'll convert your program to a primes_below function. (I don't take into account the lower bound.)
After doing this I got:

def primes_below(n):
    lis = set([p * i for p in range(2, n + 1) for i in range(2, n + 1)])
    return sorted(set(range(2, n + 1)) - lis)

First things first, you need a maximum of \$n ^ 2\$ amount of memory.
Why?
If we look at your algorithm what is \$i_{\text{max}}\$ and \$p_{\text{max}}\$?
Both are \$n\$. And so your current largest number is \$n^2\$.

You said:

  I also tried using square root but that was throwing error.

This also wouldn't work correctly.
Lets go through every combination if we were to do that with 16.

2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16

This means that 4, 6, 8, 9, 12, 16 are not prime. We should know that the primes in this range are 2, 3, 5, 7, 11, 13.
And so 10, 14, 15 are all incorrectly said as prime.

But looking at the above you should be able to see that there is no point on having \$3 * 2\$, \$4 * 2\$, \$4 * 3\$.
This is as you've already done those calculations and so you should start the range for \$i\$ at \$p\$.
And this is true for your current solution.

And so we know that we should at least use:

def primes_below(n):
    lis = set([p * i for p in range(2, n + 1) for i in range(p, n + 1)])
    return sorted(set(range(2, n + 1)) - lis)

Now we need to remove the creation of numbers greater than (or equal) \$n\$.
Rather than looking at some complex maths, we'll have a look at range.

  range(stop)
  range(start, stop[, step])

  This is a versatile function to create lists containing arithmetic progressions.
  It is most often used in for loops. The arguments must be plain integers.
  If the step argument is omitted, it defaults to 1.
  If the start argument is omitted, it defaults to 0.
  The full form returns a list of plain integers [start, start + step, start + 2 * step, ...].
  If step is positive, the last element is the largest start + i * step less than stop; if step is negative,
  the last element is the smallest start + i * step greater than stop.
  step must not be zero (or else ValueError is raised).

This means that you can use this instead of your multiplication!

From the above we know that the first number we use is \$p * p\$, this is as \$i\$ starts as \$p\$.
The largest number we want is also \$n\$.
But we don't want to remove all the numbers that are between \$p^2\$ and \$n\$,
and so we need that step.
That step will also be \$p\$.

Or in Python:

def primes_below(n):
    lis = set([i for p in range(2, n) for i in range(p * p, n, p)])
    return sorted(set(range(2, n)) - lis)

Before we say all is good, some maths!
What is the largest \$p\$ that will mean the second range contains a value?

If \$p^2 > n\$ then the second range will be empty, and so the largest \$p\$ follows the equation \$p^2 <= n\$.
And so \$p_{\text{max}} = \sqrt{n}\$.

And adding this to the range significantly improves performance.

def primes_below(n):
    lis = set([i for p in range(2, int(n ** 0.5) + 1) for i in range(p * p, n, p)])
    return sorted(set(range(2, n)) - lis)

This function is roughly ~3800 times faster than the original, at n = 5000.

Now you probably think it's good enough for this challenge, it's pretty fast!
But unfortunately no. Actually I thought I'd broke my machine when I ran it the first time, and I have 32GB of RAM!
I closed every app I had on my machine and the program still broke!
This means that you have to care about the memory and your current method doesn't.

Instead we need to limit the amount of memory to \$n\$.

To do this you can use lis = [True] * n.
And then you want to change them to False if you come across one.
And you'll want to set 0 and 1 to false at the beginning.
The same way you are at the moment.
This should get you something like:

def primes_below(n):
    lis = [True] * n
    lis[0] = lis[1] = False
    for p in range(2, int(n ** 0.5) + 1):
        for i in range(p * p, n, p):
            lis[i] = False
    return ...

Now you want to be able to return the numbers.
Python has enumerate which will give us the index and the value,
this will allow us to make a comprehension.
And so if the value is True add the index to the output.
Which will result in:

def primes_below(n):
    lis = [True] * n
    lis[0] = lis[1] = False
    for p in range(2, int(n ** 0.5) + 1):
        for i in range(p * p, n, p):
            lis[i] = False
    return (i for i, v in enumerate(lis) if v)

Since you don't want to display some numbers you'll want to implement a lower bound, I'd do this out of the function as then if you ever need the Sieve again you'll have a 'pure' one.

This can simply be another comprehension:

numbers = (i for i in primes_below(b + 1) if i < a)

And will make usage simple:

no_of_cases = int(input())
for _ in range(no_of_cases):
    a, b = map(int, input().split(" ")[:2])
    print([i for i in primes_below(b + 1) if i < a)])

This however is still too slow for my liking.
And so to make it 3 times faster, at n = 10 ** 7, you can add a check if p is prime, if it is then do what we were doing before if not go to the next number.

This results in:

def primes_below2(n):
    lis = [True] * n
    lis[0] = lis[1] = False
    for p in range(2, int(n ** 0.5) + 1):
        if not lis[p]:
            continue
        for i in range(p * p, n, p):
            lis[i] = False
    return (i for i, d in enumerate(lis) if d)

This is roughly 11500 times faster than the original, at n = 5000.
And takes about 244 seconds, on my machine, to generate all the primes below 10 ** 9.


Creative triangle stacks using for loops

I created a method, so it is easy to adjust the height of the pyramid, and the output it gives is just as you asked. This code is shorter and easier to understand in my opinion(maybe just because I wrote it), but the main difference is that it is easy to change the height of your pyramid. I named my function drawMounts(int height). Try changing height in the main method, and you will see that the pyramids easily adjust. This program makes one line at a time, prints it and repeats but the line changes slightly. height can be even or odd, it works the same. Here's the program:

public class Experiments {
    public static void main(String[] args) {
        drawMounts(3);
    }
    private static void drawMounts(int height) {
        for (int i = 0; i < height; i++) {
            String line = "";
            String ends = "";
            String middle = ".";
            String mount = "";
            System.out.print("|");
            for(int j = i; j < (height-1); j++)
                middle += "..";
            for (int dot = i; dot < (height-1); dot++)
                ends += ".";
            for(int body = (i+1); body > 0; body--)
                mount += "/\\";
            line = ends + mount + middle + mount + ends;
            System.out.print(line);
            System.out.println("|");
        }
    }
}

And here's the output when height is equal to 3:

|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|

And this is when height is 6, just so you get an idea of what changing height does:

|...../\........../\.....|
|..../\/\......../\/\....|
|.../\/\/\....../\/\/\...|
|../\/\/\/\..../\/\/\/\..|
|./\/\/\/\/\../\/\/\/\/\.|
|/\/\/\/\/\/\/\/\/\/\/\/\|


Conditional Concatenation of a Pandas DataFrame

There's no need to create a lambda for this.

Let's suppose we have the following dataframe:

my_df = pd.DataFrame({
    'Apple':  ['1', '4', '7'],
    'Pear':   ['2', '5', '8'],
    'Cherry': ['3', np.nan, '9']})

Which is:

Apple Cherry Pear
   1      3    2
   4    NaN    5
   7      9    8

An easier way to achieve what you want without the apply() function is:

use iterrows() to parse each row one by one.
use Series() and str.cat() to do the merge.

You'll get this:

l = []
for _, row in my_df.iterrows():
    l.append(pd.Series(row).str.cat(sep='::'))

empty_df = pd.DataFrame(l, columns=['Result'])

Doing this, NaN will automatically be taken out, and will lead us to the desired result:

Result
1::3::2
   4::5
7::9::8

The entire program may look like:

import pandas as pd
import numpy as np

def merge_columns(my_df):
    l = []
    for _, row in my_df.iterrows():
        l.append(pd.Series(row).str.cat(sep='::'))
    empty_df = pd.DataFrame(l, columns=['Result'])

    return empty_df.to_string(index=False)

if __name__ == '__main__':
    my_df = pd.DataFrame({
        'Apple': ['1', '4', '7'],
        'Pear': ['2', '5', '8'],
        'Cherry': ['3', np.nan, '9']})
    print(merge_columns(my_df))

There are other things that I added to my answer as:

if __name__ == '__main__'
added the logic into its own function so that you can reuse it later

As  @MathiasEttinger suggested, you can also modify the above function to use list comprehension to get a slightly better performance:

def merge_columns_1(my_df):
    l = [pd.Series(row).str.cat(sep='::') for _, row in my_df.iterrows()]

    return pd.DataFrame(l, columns=['Result']).to_string(index=False)

I'll let the order of the columns as an exercise for OP.


Early Return

You can return early to reduce the nesting of your if statements:

if (plugins.isEmpty()) {
    plugin = null;
    return;
}

Also note that I changed plugins.size() > 0 to !plugins.isEmpty(), I think it's more readable.

Plugins Field

Code like this:

plugins = pluginManager.getPlugins(); // assign field

plugins = filterPlugins(searchParam); // method expects plugins field to be assigned,
                                      // but doesn't work on it but returns instead

Can be a bit confusing. I would change it to:

plugins = filterPlugins(pluginManager.getPlugins(), searchParam);

And then change filterPlugins to:

private List<Plugin> filterPlugins(final List<Plugin> plugins, final String searchParam )

plugin field

I would still like to see the declaration of plugin as well as the selectPlugin method. As mentioned in the comments, it looks a bit like it might be bad design.


This is a performance issue:

primes_below_sqrt = {i for i in prime_set if i <= sqrt(x)}

By using a set comprehension instead of a generator expression, you are actually making a copy of the subset.


Collect all fields having given Modifier(s)

I've played with your code and have a few broad observations....

The code is neat enough and generally readable.
JavaDocs are not complete - return values are not documented
@since JavaDoc tag traditionally records a version number, not a date.

I don't think there is a generally 'better' way to do what you are doing, but I think some of the specific details are worth commenting on..... and my last paragraph is an important one, so please make sure you consider it....

Some more specific comments:

Just check that you really need both getFields methods to be public. Exposing just the second version may be a better option and make the getFields(Class<?> instanceClass) version private. This is a matter of style and usage. In general I feel people make things public when they shouldn't. Whether that is right this time or not is your decision though
I feel you overuse the Collections.unmodifiableList(...). Generally this is only useful to protect data that is encapsulated in your class. In this case, the data is not something you need to protect, and worse, you need to 'undo' the unmodifiable state of the list in your exclude/include function. In this case, there is no value in making the lists read-only and if a 'user' decides they want to change the list they can do it without damaging your class, and all you do is make it harder for them (and yourself).
including the LambdaJ function dependency is perhaps unnecessary. The logic you want to do can be accomplished in a few lines with an iterator and a set. The burden of maintaining a dependency on an external library is potentially significant. If you have other needs for LambdaJ then sure, use it, but otherwise you may be satisfied with:

Iterator<Field> it = fields.iterator();
Set<String> names = new HashSet<String>();
while (it.hasNext()) {
    Field f = it.next();
    if (!names.add(f.getName())) {
        it.remove();
    }
}

Finally, I have to question why you want to remove 'shadowed' fields at all. They are different fields and you are losing information if you remove them. Are you sure you want them gone?


Create 'worst case test' data for compression test

This is a cool idea! Here are some thoughts I had:
What are these magic numbers?
You have 4 magic numbers in your main loop: 0x10000, 0xc369, 0xFFFF, and 2. What do they mean? It looks like 0x10000 is the number of 2-byte words you're writing to the file. It's also the limit of a 16-bit number. It would be nice if there were a named constant for that. Perhaps something like:
const int kWordsPerFile = 0x10000;

or
const int kMax16BitValue = 0x10000;

Or something along those lines. (Technically it's 1 more than the max, so maybe something more descriptive.)
Honestly, I can live with 0xFFFF but it wouldn't hurt to give it a name like kLSWMask (where LSW is least significant word) or something similar.
You could get rid of the 2 by making t be a uint16_t and then using sizeof(t).
That leaves 0xc369. I have no idea what it is. I assume this is some sort of linear congruential pseudo-random number generator, but I'm not really well versed in such things. How is it derived? What significance does it have? Give it a name so it's understandable to someone else 6 months from now.
Comments
I'm a big fan of self-documenting code. However, in this case, it would be nice to have at least a sentence explaining what the loop does. Coming across this code in the code base I work on would leave me scratching my head. I'd have to go back through source control comments to see if there was any clue of what it was about. Maybe just a comment like:
// Generate some pseudo-random numbers where no 2 bytes are repeated

would really help a lot! And if you have a link or a short sentence to explain the algorithm, that would be nice, too.


I feel as if my quicksort can be made more efficient, but what?

I don't like seeing arrays passed as parameters.

void quicksort(int list[], int low, int high)
//                  ^^^^^

Inside the function all similarity to an array has disappeared. It has decayed into a pointer. By using the array like syntax you might catch people out that want to treat it as an array (which is a real maintenance issue).

If this code is C then just pass as a pointer.
If this code is C++ then pass as a reference to an array, or use a container type and pass by reference (I prefer the container option as you can template it).

In quick pre-condition checks at the head of a function like this.
There is no need for the else part.

if(low >= high)
    return;
else

It looks neater and saves you a level of indentation.

One variable per line.
Also give the variables more meaningful names.

    int pivot = low, i = low, j = high;

Also I would say that pivot is really the value you are pivoting around. Not the location of the value you are pivoting around.

    int pivot = list[<location Of Pivot Value>]; // See below for more.

Pretty sure there is a bug here i < high is not correct.

        while(list[i] <= list[pivot] && i < high)

Same thing here. Pretty sure there is a bug here j > low is not correct.

        while(list[j] > list[pivot] && j > low)

Yep. You are correct the break is ugly here.

        if(i < j)
        {    std::swap(list[i], list[j]);
        }

You are only doing this (below) to prevent your self choosing the same pivot point each time. So you should choose a different technique to choose the pivot point. Why not the element in the middle of the list?

    int temp = list[pivot];
    list[pivot] = list[j];
    list[j] = temp;

You pass the location of the first and last element in the array.

    quicksort(list, low, j-1);
    quicksort(list, j+1, high);

It is more C++ like to use first and one past the point you consider end. It also makes the code look neater try it and see.


It's not a good practice to put everything into the request parser. You can put there your formParser, but let an UserController.* handle the rest.

Think about your userActions (UserController.updateUsername) in a more abstract way, for example if you decide to setup an admin backend, where you have some other routes, you would like to reuse your code..

If you consider, to use a seed script, it could directly talk to the UserController, or modify values from a CommandLineTool.

The best scenario would be, if your routes just points to the controllers, so you could define a bunch in a single file, to see all your endpoints, and where they are pointing too.

One more hint: use a middleware to parse the form data.


How can I speed up my IDA* algorithm for N-puzzle?

The code does not compile as it is:

The solve function's signature contains unnecessary code
def solve(initial_state):path = solve(initial_state)

A NumPy array cannot be initialized like np.array([8 7 3],[4 1 2],[0 5 6])
Globals are not initialized
constant.GOAL_STATE is not defined

Review

In the method search, checking if n not in path is an expensive operation that can be optimized using a set or a dictionary. This drops the runtime on my machine by 70%. A dictionary seems to be a good option since it keeps insertion order (if Python >= 3.7) and can be used as a queue.
manhattan_heuristic uses many times np.where, it can be optimized. An option is to iterate through the puzzle and when an element is different from the goal, calculate the difference. Converting GOAL_STATE to a dictionary will also improve the performance, instead of calling position1 = np.where(state1 == number) every time.
nextnodes also uses np.where two times which can be avoided. For example, instead of calling zero = np.where(node.state == 0) every time, Node can contain the coordinates of zero as a class property.
Naming: variable SIZE and SIZE2 are confusing because one is a generator and the other is the size of the puzzle. Consider giving more meaningful names.
Globals: try to reduce the use of globals as much as possible as it makes the code hard to test.

Note: this is not a comprehensive review, I think there is still room for improvements, I hope you will get more reviews.
Runtime after the improvements:

Puzzle
Original
Improved

3x3
0.696 s
0.097 s

4x4
7.021 s
0.549 s

Reworked code:
from time import perf_counter as pc

import numpy as np

GOAL_STATE = [[]]
GLOBAL_STATE_DICT = {}
N = 0

class Node:
    def __init__(self, state, manhattan, zero_pos):
        self.state = state
        self.heuristic = manhattan
        self.zero_pos = zero_pos

    def __str__(self):
        return f"state=\n{self.state}\nheuristic={int(self.heuristic)}"

    def __eq__(self, other):
        return np.array_equal(self.state, other.state)

    def __repr__(self):
        return f"state=\n{self.state}\nheuristic={int(self.heuristic)}"

    def __hash__(self):
        return hash(self.state.tobytes())

def customSort(node):
    return node.heuristic

def nextnodes(node):
    zero = node.zero_pos

    r, c = map(int, zero)
    directions = ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1))
    nodes = []
    for direction in directions:
        if 0 <= direction[0] < N and 0 <= direction[1] < N:
            tmp = np.copy(node.state)
            goal = GLOBAL_STATE_DICT[tmp[direction]]

            tmp[direction], tmp[zero] = tmp[zero], tmp[direction]

            dir_goal_distance = manhattan_distance(direction, goal)
            goal_zero_distance = manhattan_distance(goal, (r, c))

            nodes.append(Node(tmp, node.heuristic - dir_goal_distance + goal_zero_distance, direction))
    return sorted(nodes, key=customSort)

def manhattan_distance(a, b):
    return abs(b[0] - a[0]) + abs(b[1] - a[1])

def manhattan_heuristic(state):
    distance = 0
    for i in range(N):
        for j in range(N):
            num = state[i][j]
            if num != GOAL_STATE[i][j] and num != 0:
                goal = GLOBAL_STATE_DICT[num]
                distance += manhattan_distance((i, j), goal)
    return distance

def search(path, g, threshold):
    node = list(path.keys())[-1]

    f = g + node.heuristic

    if f > threshold:
        return f
    if np.array_equal(node.state, GOAL_STATE):
        return True

    minimum = float('inf')
    for n in nextnodes(node):
        if n not in path:
            path[n] = None
            tmp = search(path, g + 1, threshold)
            if tmp == True:
                return True
            if tmp < minimum:
                minimum = tmp
            path.popitem()

    return minimum

def solve(initial_state):
    zero = np.where(initial_state == 0)
    initial_node = Node(initial_state, manhattan_heuristic(initial_state), zero)
    threshold = initial_node.heuristic
    # The dictionary keeps insertion order since Python 3.7 so it can be used as a queue
    path = {initial_node: None}
    while 1:
        tmp = search(path, 0, threshold)
        if tmp == True:
            print("GOOD!")
            return path.keys()
        elif tmp == float('inf'):
            print("WRONG!")
            return False
        threshold = tmp

def define_goal_state(n):
    global GOAL_STATE
    global N
    global GLOBAL_STATE_DICT

    m = [[0] * n for i in range(n)]
    dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
    x, y, c = 0, -1, 1
    for i in range(n + n - 2):
        for j in range((n + n - i) // 2):
            x += dx[i % 4]
            y += dy[i % 4]
            m[x][y] = c
            c += 1

    GOAL_STATE = np.array(m)
    N = len(GOAL_STATE)
    GLOBAL_STATE_DICT = {m[r][c]: (r, c) for r in range(N) for c in range(N)}

tests = {'3x3': np.array([[8, 7, 3], [4, 1, 2], [0, 5, 6]]),
         '4x4': np.array([[13, 2, 10, 3],
                                [1, 12, 8, 4],
                                [5, 0, 9, 6],
                                [15, 14, 11, 7]])}

for name, puzzle in tests.items():
    define_goal_state(len(puzzle))
    print('Puzzle:\n', puzzle)
    t0 = pc()
    path = solve(puzzle)
    t1 = pc()
    print(f'{name} depth:{len(path)} runtime:{round(t1 - t0, 3)} s')


Powershell script to verify Linux-generated md5sum file

here are a few changes i would make. [grin] the ideas ...

use Get-Content instead of ReadLines()
the speed difference is not large unless you are dealing with a very large number of files. go with the standard cmdlets unless there is a meaningful benefit from doing otherwise.
test to see if the file exists
build a [PSCustomObject] to hold the resulting items that you want
keep those PSCOs in a collection
view your hash failure items after the full test ends

what it does ...

sets the constants
builds a test file to work with
remove the entire #region/#endregion block when you are ready to use your own data.
reads in the hash list file
iterates thru the resulting array
splits out the file name and hash value
builds the full file name to check
tests to see if that file exists
if YES, gets the file hash and saves it
if NO, sets the file hash $Var to '__N/A__'
builds a PSCO with the properties that seem useful
sends that to the $Result collection
gets the hash failures from the collection and displays them
if all you want it the count, wrap that all in @() and add .Count to the end.

the code ...
$SourceDir = $env:TEMP
$HashFileName = 'FileHashList.txt'
$FullHashFileName = Join-Path -Path $SourceDir -ChildPath $HashFileName

#region >>> make a hash list to compare with
#    remove this entire "#region/#endregion" block when ready to work with your real data
$HashList = Get-ChildItem -LiteralPath $SourceDir -Filter '*.log' -File |
    ForEach-Object {
        '{0} {1}' -f $_.Name, (Get-FileHash -LiteralPath $_.FullName-Algorithm 'MD5').Hash
        }
# munge the 1st two hash values
$HashList[0] = $HashList[0] -replace '.{5}$', '--BAD'
$HashList[1] = $HashList[1] -replace '.{5}$', '--BAD'

$HashList |
    Set-Content -LiteralPath $FullHashFileName
#endregion >>> make a hash list to compare with

$Result = foreach ($Line in (Get-Content -LiteralPath $FullHashFileName))
    {
    $TestFileName, $Hash = $Line.Split(' ')
    $FullTestFileName = Join-Path -Path $SourceDir -ChildPath $TestFileName
    if (Test-Path -LiteralPath $FullTestFileName)
        {
        $THash = (Get-FileHash -LiteralPath $FullTestFileName -Algorithm 'MD5').Hash
        }
        else
        {
        $THash = '__N/A__'
        }
    [PSCustomObject]@{
        FileName = $TestFileName
        CopyOK = $THash -eq $Hash
        OriHash = $Hash
        CopyHash = $THash
        }
    }

$Result.Where({$_.CopyOK -eq $False})

output [with the 1st two hash values deliberately munged] ...
FileName                  CopyOK OriHash                          CopyHash
--------                  ------ -------                          --------
Genre-List_2020-07-07.log  False 7C0C605EA7561B7020CBDAE24D1--BAD 7C0C605EA7561B7020CBDAE24D140E40
Genre-List_2020-07-14.log  False 20F234ACE66B860821CF8F8BD5E--BAD 20F234ACE66B860821CF8F8BD5EC144D


DBSCAN "region query" too slow; implement a tree?

You don't provide much information, which is unfortunate, since this kind of optimization problem relies on knowing how to "skew" the code in order to get better performance.

For example, are your points constant? If you are always searching the same set of 27k points - for example, cities or road termini or railroad stations or whatever - then you can pre-compute lots of data about those points to make the code faster.

Are the points accumulated gradually over time? Could you perform an expensive computation on each point safely, knowing that the various points are collected at some interval that allows for that?

Are the points close together or far apart, relative to the likely neighborhood distances? That is, can you estimate the number of points that will be in the likely neighborhood queries?

Is your program memory-constrained? Can we trade memory allocation for performance?

Are the eps values - the neighborhood distances - truly variable? Or is there a static list (1km, 10km, 25km, 50km) that the user chooses from?

All these questions, and more, could be used to tune the code for speed. When you're asking a speed question, there's no such thing as too much data!

Finally, what flavor of python are you using? PyPy? Cpython? Jython? Cython?

With that out of the way, let me make a few "low hanging fruit" suggestions. I'll assume you're using "the python that came with my system" - meaning Cpython 2.7 or 3.4+.

The cpython compiler isn't nearly as smart as you might like. Let's look at the generated code from your function (I put it in test.py in a class named C):

$ python2
Python 2.7.13 (default, Apr 23 2017, 16:50:35)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> import dis
>>> dis.dis(test.C.find)
  3           0 BUILD_LIST               0
              3 STORE_FAST               2 (nearby)

  4           6 SETUP_LOOP             230 (to 239)
              9 LOAD_FAST                0 (self)
             12 LOAD_ATTR                0 (data)
             15 GET_ITER
        >>   16 FOR_ITER               219 (to 238)
             19 STORE_FAST               3 (pt)

  6          22 LOAD_GLOBAL              1 (map)
             25 LOAD_GLOBAL              2 (math)
             28 LOAD_ATTR                3 (radians)
             31 LOAD_FAST                1 (p)
             34 LOAD_ATTR                4 (x)
             37 LOAD_FAST                3 (pt)
             40 LOAD_ATTR                4 (x)
             43 LOAD_FAST                1 (p)
             46 LOAD_ATTR                5 (y)
             49 LOAD_FAST                3 (pt)
             52 LOAD_ATTR                5 (y)
             55 BUILD_LIST               4
             58 CALL_FUNCTION            2
             61 UNPACK_SEQUENCE          4
             64 STORE_FAST               4 (px)
             67 STORE_FAST               5 (ptx)
             70 STORE_FAST               6 (py)
             73 STORE_FAST               7 (pty)

  7          76 LOAD_FAST                4 (px)
             79 LOAD_FAST                5 (ptx)
             82 BINARY_SUBTRACT
             83 STORE_FAST               8 (dx)

  8          86 LOAD_FAST                6 (py)
             89 LOAD_FAST                7 (pty)
             92 BINARY_SUBTRACT
             93 STORE_FAST               9 (dy)

  9          96 LOAD_GLOBAL              2 (math)
             99 LOAD_ATTR                6 (sin)
            102 LOAD_FAST                9 (dy)
            105 LOAD_CONST               1 (2)
            108 BINARY_DIVIDE
            109 CALL_FUNCTION            1
            112 LOAD_CONST               1 (2)
            115 BINARY_POWER
            116 LOAD_GLOBAL              2 (math)
            119 LOAD_ATTR                7 (cos)
            122 LOAD_FAST                6 (py)
            125 CALL_FUNCTION            1
            128 LOAD_GLOBAL              2 (math)
            131 LOAD_ATTR                7 (cos)
            134 LOAD_FAST                7 (pty)
            137 CALL_FUNCTION            1
            140 BINARY_MULTIPLY
            141 LOAD_GLOBAL              2 (math)
            144 LOAD_ATTR                6 (sin)
            147 LOAD_FAST                8 (dx)
            150 LOAD_CONST               1 (2)
            153 BINARY_DIVIDE
            154 CALL_FUNCTION            1
            157 LOAD_CONST               1 (2)
            160 BINARY_POWER
            161 BINARY_MULTIPLY
            162 BINARY_ADD
            163 STORE_FAST              10 (a)

 10         166 LOAD_CONST               1 (2)
            169 LOAD_GLOBAL              2 (math)
            172 LOAD_ATTR                8 (asin)
            175 LOAD_GLOBAL              2 (math)
            178 LOAD_ATTR                9 (sqrt)
            181 LOAD_FAST               10 (a)
            184 CALL_FUNCTION            1
            187 CALL_FUNCTION            1
            190 BINARY_MULTIPLY
            191 STORE_FAST              11 (c)

 11         194 LOAD_CONST               2 (6371.0)
            197 LOAD_FAST               11 (c)
            200 BINARY_MULTIPLY
            201 STORE_FAST              12 (d)

 12         204 LOAD_FAST               12 (d)
            207 LOAD_FAST                0 (self)
            210 LOAD_ATTR               10 (eps)
            213 COMPARE_OP               0 (<)
            216 POP_JUMP_IF_FALSE       16

 13         219 LOAD_FAST                2 (nearby)
            222 LOAD_ATTR               11 (append)
            225 LOAD_FAST                3 (pt)
            228 CALL_FUNCTION            1
            231 POP_TOP
            232 JUMP_ABSOLUTE           16
            235 JUMP_ABSOLUTE           16
        >>  238 POP_BLOCK

 14     >>  239 LOAD_FAST                2 (nearby)
            242 RETURN_VALUE

First, have a look at "line 10" - the block of code that starts with a "10" in the left-most column. That code corresponds to this python:

    c = 2*math.asin(math.sqrt(a))

The Python VM is a stack machine, so every opcode either takes something off the stack, puts something on the stack, or both. For example, the various LOAD_ ops put things onto the stack. The CALL_FUNCTION op calls a function (which is stored on the stack) with a number of arguments. And BINARY_MULTIPLY takes two arguments off the stack, multiplies them, and pushes the result back onto the stack.

There's a couple of optimization opportunities here that are good "rules of thumb." You can take this knowledge and apply it to any Cpython code you need to speed up (note: Cpython).

First, there's that 2 * at the front of the expression. That's fairly harmless, except that on the very next line you multiply by 6371.0, and you never do anything else with the c variable - it's just a temp. So to squeeze out some performance, go ahead and move the 2* to the next line. It turns out that the compiler will go ahead and do constant math in the same expression, so you can say 6371.0 * 2 * c and it will collapse that to a single constant.

Second, note that there's this sequence of lookups all over the place:

            169 LOAD_GLOBAL              2 (math)
            172 LOAD_ATTR                8 (asin)

In general, Python believes that any operation might cause the result of a name lookup to change. Because you can return any type, and any type can overload pretty much any operation, so why shouldn't it be possible for 2 * math.asin(x) to change the function pointed to by math.sqrt?

Because of this, and because name lookups like this really can be expensive (remember property methods and descriptors), you generally want to cache dotted-name lookups in a local variable if you're going to be looping with them:

asin = math.asin
sqrt = math.sqrt

Please note: This is not the same as doing from math import asin because that will still create a "global" name, and require a LOAD_GLOBAL operation, instead of a LOAD_FAST. Notice the FAST in the opcode name. ;-)

The same thing is true for almost every dotted name - if you are going to use it more than once, put it in a local variable.

One thing that might not be obvious is that you can cache "bound methods" - that is, method lookups like nearby.append. So you can also do:

nearby_append = nearby.append

...

nearby_append(pt)

And squeeze out another lookup.

But wait, there's more!

Because before you start doing that "peephole" optimization stuff, you need to look at improving your code in some other ways. Take a look at this:

def find(self, p):
    nearby = []
    for pt in self.data:
        # Haversine algorithm
        px, ptx, py, pty = map(math.radians, [p.x, pt.x, p.y, pt.y])

For the purposes of this function, the p object is a constant. So why do you keep doing the same conversion on it? Remember that map just applies the given function to each argument in turn. So you're calling math.radians on p.x and p.y 27000 times. Guess what? The answer isn't going to change!

Of course, I suspect that none of your points are going to change. That is, I suspect that once you create a point object, it doesn't get updated. So I think you would benefit from performing this conversion in the class initializer and storing the radian values in the object:

class Point:
    def __init__(self, lon, lat):
        self.x = lon
        self.x_radians = math.radians(lon)   # <- HERE
        self.y = lat
        self.y_radians = math.radians(lat)   # <- HERE
        self.cluster = None
        self.neighbors = 0

If you do that, you can eliminate that entire map call, and just retrieve the values. Yes, you pay an up-front cost of 27000 extra function calls, but it beats doing it in your find loop. (If you can't pay that cost, you could certainly do it as a separate loop at the front of your find function. You're going to do it anyway, and this lets you store the result.)

Also of note: math.cos(py) and math.cos(pty). You can certainly compute the cosine of py once at the top of the function. And if you're going to call this function a lot, it's probably worth storing the cosine(y) for all the points in the initializer.

Heuristics, anyone?

Another suggestion is simply to guess what's a neighbor and what's not. You've got a nice calculation there, with lots of trigonometry. But keep in mind what it's doing: it's trying to compute distance on a sphere, which is basically distance along a circle. The key word is circle.

At θ = 45°, cosθ is √2/2 as is sinθ. The sum of the two is √2, which is the maximum sum for a circle of radius 1. Thus, you know that for whatever distance N defines your neighborhood, the sum of cosine and sine will be less than or equal to √2 * N.

If your points are widely separated - that is, if you're dealing with cities and not the entrances to buildings in the same town - you can implement a heuristic: change √2 into 2.5 to allow for spherical error, and compute the corners of a "square" centered at p with sides 2 * 2.5 * N. Then just compare pt.x and pt.y with the min/max x and y of this square. Only if the point is inside the square do you perform the "expensive" computations. This adds a set of 4 comparisons to your loop, but eliminates the trig calls for all the non-matching candidates. Hopefully, that's most of the points.

This is important! If your points are heavily clustered, there's no sense having a heuristic to guess if one point is a neighbor of another - because you know the answer is yes! In that case, it would make more sense to develop a reverse heuristic, that says "here's a square contained in the circle. If the point is inside this square you know it's a neighbor, otherwise do the computation."  The objective with heuristics it to produce a fast computation that handles 75% or more of cases. If your data is biased, make the heuristic align with the biases!

Finally, another simple optimization would be to take your self.eps value and divide it by the various factors you are presently using to multiply. This can be done outside the loop, once, and saves you some cycles.

Larger-scale changes

First, don't forget that if A is a neighbor of B, then B is a neighbor of A. Make sure you are only looping over the "higher" values in your N-squared neighbor search:

for i, p1 in enumerate(points):
    for p2 in points[i+1:]:
        # etc.

You just have to be sure and add A to B's neighborhood and B to A's neighborhood at the same time.

Depending on what you're doing, there are a couple of geospatial data structures that you might profitably use. Two obvious ones are a hash of some sort and a K-d tree. The hash approach will work if your points are clustered and if you can determine a key generation algorithm that will reflect this. For example, if you know that your points are GPS coordinates in major metropolitan areas (New York, Los Angeles, Dallas, Chicago) then a hash key that "rounded" the coordinates to the nearest city center might be adequate. (Or truncated the lat/lon to, say, the nearest 5 degrees.) In this case, you'd want to have a hash value with lots of collisions. The collisions would be the likely neighbors. So you would iterate over the hash keys (equal to, say, 10% of the points) and identify which buckets you would search in. On the other hand, if the points are more distributed, or the clustering isn't obvious, then go with the K-d tree.

The K-d tree is a binary tree (or binary-search-tree if you're a child of the 21st century) that can be used for locating any point. To find neighboring points using your distance function, you would simply do the distance computation at each node of the tree. The special case would be when a node's key value is within the heuristic neighborhood of your target point, you'll have to traverse both children of the node, to find any other nodes in the other half of the tree that might be in the neighborhood. For example, if a node is a lat node, with lat=A, and your target point has lat=A-2km, then for neighborhood=5km you'll have to search on either side of that node.

Also, note that you'll need to develop a strategy for nodes with equal values. For example, if two points have the same longitude, would you store a list-of-points in the node, or make a rule that says "sort by lowest latitude and put the other points in the right hand subtree"? It's up to you, but you need to handle it. (I suggest the latter.)


How can I improve this version of the board game Mastermind?

The first thing I notice is that you're "manually" handling both color and position. This isn't actually necessary if you set everything up using simple arrays.

An array is, by definition, an indexed list of values. So if you use a simple array for your code and the pegs, then positions are the array's indices and colors are its values. This simplifies things considerably.

For instance, to find exact (color and position) matches, you only need to check if code[i] === pegs[i]. And to check if a peg matches anywhere in the code, you only need to check code.indexOf(peg[i]) !== -1. So if you can get something like this:

var code = ["white","black","red","blue","green"];  // the code
var pegs = ["white","black","blue","red","orange"]; // the player's selections

it'll make the checking a lot easier.

Now, along the way you'll need to do some extra work to keep track of the number of matches, and make sure you're not double-matching stuff. I.e. you need to pare down your arrays as you go, so they only contain the remaining unmatched values.

Here's an example:

function evaluateSolution(code, pegs) {
  var i, l,
      foundIndex,
      exactMatches = 0,
      valueMatches = 0;

  // copy the arrays, so we don't ruin the orignals
  code = code.slice(0);
  pegs = pegs.slice(0);

  // First pass: Look for value & position matches
  // We're looping "backwards", so we can safely remove items
  // "behind us"
  for( i = pegs.length - 1 ; i >= 0 ; i-- ) {
    // If there's a match, remove the matched index from both
    // the code and the pegs so it isn't matched again later.
    if(pegs[i] === code[i]) {
      exactMatches++;
      pegs.splice(i, 1);
      code.splice(i, 1);
    }
  }

  // Now, pegs and code only contain unmatched values

  // Second pass: Look for value matches anywhere in the code
  for( i = 0 , l = pegs.length ; i < l ; i++ ) {
    // attempt to find the peg in the remaining code
    foundIndex = code.indexOf(pegs[i]);
    if( foundIndex !== -1 ) {
      valueMatches++;
      // remove the matched code peg, since it's been matched
      code.splice(foundIndex, 1);
    }
  }

  // Now, return the number of exact and inexact matches
  // as an object, so it's easy to use
  return {
    exactMatches: exactMatches,
    valueMatches: valueMatches,
    totalMatches: exactMatches + valueMatches
  };
}

If you feed the arrays above to evaluateSolution() you'll get this back:

{
  exactMatches: 2,
  valueMatches: 2,
  totalMatches: 4
}

If exactMatches === code.length, then congrats, you've won! Otherwise, use the numbers to render the hint.

Other observations:

You leave a lot of blank lines in your code, but the non-blank lines are pretty crammed (e.g. your whitespace-less for-loop declarations). Give you code (and the reader) some space to breathe.
I looked briefly at the code on GitHub, and there's a lot going on. Too much really. But here's a hint: You can build most of HTML using JavaScript. Copy/pasting the HTML for each "turn" and giving it a new ID is a nightmare to deal with. Just loop and create elements in code.


First up, let's both simplify your low level Stack class, and correct the Generics at the same time.

Stack

The issues with the generics are "obvious" by the numerous times you cast values that should be generically correct anyway.

You also have overly complicated logic in your push method:

public void push(T item){
    Node p = new Node((Comparable) item);
    if(head == null){
        head = p;
        return;
    }
    p.next = head;
    head = p;

}

That can be simply (note, this requires a change to Node that I describe in a moment):

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

Right, the change to Node is to add the next to the constructor:

private class Node{
    private final T data;
    private final Node next;

    public Node(T data, Node next){
        this.data = data;
        this.next = next;
    }
}

The System.exit(-1) error handling is also really horrible.... use exceptions!

Finally, why do you have a getHead() method on the Stack? It returns a value that is a private-context Node, so nobody can actually call that method.... right? I am half-surprised that Java lets that compile.

The "final" Stack class could look like:

public class Stack<T>{

    private class Node{
        private final T data;
        private final Node next;

        public Node(T data, Node next){
            this.data = data;
            this.next = next;
        }
    }

    private Node head;

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

    public T pop(){
        if(head == null){
            throw new IllegalStateException("Cannot pop an empty Stack");
        }

        T item = head.data;
        head = head.next;
        return item;

    }

    public T peek(){
        if(head == null){
            throw new IllegalStateException("Cannot peek an empty Stack");
        }
        return head.data;
    }

    public boolean isEmpty(){
        return head == null;
    }
}

SortedStack

This class has some simpler problems - naming, and style. It also has some algorithmic problems that may be improved.

s1 and s2 are horrible, horrible names. stack and temp would be better. But, really, there's no reason to have temp at all, you can create it for the duration of the push method only - it does not need to hang around when empty.

You also have the following, very baffling method. This is a "WTF" thing:

public int compareTo(T other){
    return compareTo(other);
}

Please explain that to me? ;-)

Throw it away!

While we are throwing things away, throw out the size as well, it's a distraction, and unnecessary.

Talking about throwing things out..... did you throw out the peek() method when it should actually be there?

One small comment on this code segment:

if((s1.peek().compareTo(item) > 0) || (s1.peek().compareTo(item) == 0)){

How about ( ;-) ):

if(s1.peek().compareTo(item) >= 0) {

Now, ignoring the push(T) method, the rest of the SortedStack class could simply be:

public class SortedStack<T extends Comparable<T>> {

    private final Stack<T> stack;

    public SortedStack(){
        stack = new Stack<>();
    }

    public T peek() {
        return stack.peek();
    }

    public T pop(){
        return stack.pop();
    }

    public boolean isEmpty(){
        return stack.isEmpty();
    }

    public void push(T item) {
        //TODO - fill this in ;-)
    }

}

Now, abut that push method.... how about:

public void push(T item) {
    Stack<T> temp = new Stack<>();

    // stash away all values less than the new item
    while (!stack.isEmpty() && stack.peek().compareTo(item) < 0) {
        temp.push(stack.pop());
    }

    // keep the item
    stack.push(item);

    // restore all the smaller items.
    while (!temp.isEmpty()) {
        stack.push(temp.peek());
    }
}


PreparedStatement for closable recordset and connection

Starting out with your first question: no, there isn't. But you may put the result set into another nested try block. Still not super-elegant, but a bit better in my opinion:

try (
    Connection connection = dataSource.getConnection();
    PreparedStatement statement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
) {
    statement.setInt(1, page);
    statement.setInt(2, size);
    try (ResultSet rs = statement.executeQuery()) {
        while(rs.next()) {
            list.add(new StateEntity(rs.getString("stateId"), rs.getString("stateName")));
        }
    }

Regarding the method itself: why do you return an iterator instead of the list itself? This severely limits the capabilities of the return value without any benefit. (E.g. you cannot use size() or stream() which you could do with the list.)

Regarding the MySql class now:

Are you aware that you actually create an anonymous subclass with the map construction using curly braces and an object initializer? I never found this on par with the problem solved here. Fortunately, Java 9 brought us Map.of, so I recommend replacing this construct with

private static Map<String, String> parameters = Map.of(
    "authReconnect", "true",
    ...
);

Regarding the query = ...stream...reduce...orElse: you can achive the same by simply using a joining collector:

String query = parameters.entrySet().stream()
    .map(p -> p.getKey() + "=" + p.getValue())
    .collect(Collectors.joining("&"));

The MySql class in itself is just global variables. This is "somewhat ok" as long as you don't employ advanced dependency injection possibilities like spring or a CDI container, but keep in mind that these globals are generally regarded as bad. Advice: read up on dependency injection, and see what options there are.


A couple of comments:

Shortening code is not a goal - readability and maintainability is (which may, but not neccessarily, shorten it).
The code mixes net code, graphics code, encoder code and UI code. Separating these into separate functions/classes will be very good. Just remember that (as a general rule), one function should do one thing.
Always use braces, even when it's for a single statement where it's not required.

if (!tcp.Connected)
{
    tcp.Connect(adress);
}

Similarly, I'd suggest putting brackets around the !xxx in the if statement. Not needed, but can aid understandability.

while ((!tcp.Connected) && (!CTS.IsCancellationRequested))

What does 13369376 represent?  Define the set of constants (SRCCOPY etc) that you're using and then use those.
TcpClient.Connect is a blocking call - depending on your use, you may want to consider rewriting using BeginConnect instead. One problem is that when in the middle of a connect, you can not check CTSSend for a cancellation.
You need to rethink your exception handling. At the moment, your code puts up a message box, requiring a response. You do not want to mix UI and non-UI code like this
The exception-catching occurs in the middle of a loop, so if it happens once, it's likely to happen again and again...each time requiring acknowledgement of the message box.
Catch specific exceptions (SocketException) rather than general ones (Exception). You can have multiple catches if you need them.
If you're using bsize to determine if the screen has changed, it'll be unreliable. You might end up with two images that have the same size even if the images are different.
The code grabs images as quickly as possible, possibly discarding most of them (if my understanding is correct) - this seems uneccessary. Why not grab an image (say) every 1 second? In which case you can set up something like a System.Timers.Timer instance and get the image when that is triggered.
You should probably allocate a new MemoryStream, rather than reusing it. If you're doing that to "save time", it 'probably' doesn't matter compared with the speed of network traffic and image conversion.
What happens when the window size changes/minimized etc, or is it guaranteed to have a fixed size?
In regards to your edit: Rather than a void return, either return a bool or (preferably) define an enum (CancelRequested, Connected) and return that.

Edit in response to (first) comment:

If you have 10 stacked braces at the end of the method, the method is too long. Break it up rather than remove the braces.
re MemoryStream - it'll gain readability. One thing though that you may want to do is to set an initial capacity (say, rc.Width*rc.Height) - MemoryStream itself reallocates memory/copies data on resizing.
Have you tried using a different image format, say png, rather than jpeg. It may be quicker to compress or smaller, depending on the type of image.
You could also try spliting the image up into quandrants/etc, compressing & sending those and reassembling them at the other side. It may be overall quicker.
And of course, if you want 'quicker', always base it on actual timings rather than feelings :)


Late response to this, but all I can suggest is leveraging the per-component math of HLSL better in your shaders...

Vertex Shader

    float xCoordMultiplication                  : register (c13);
    float yCoordMultiplication                  : register (c14);

Make that a float2

    float2 xyCoordMultiplier   : register (c13) : register (c14);

I think that's how you tie two different registers to one global. Might want to double check MSDN HLSL reference to be sure, though.

With your xy multiplier now a float 2, you can change this...

        OUT.texCoord = float2(IN.texCoord.x * xCoordMultiplication,
                              IN.texCoord.y * yCoordMultiplication);

... to this ...

        OUT.texCoord = IN.texCoord.xy * xyCoordMultiplier.xy;

You save yourself having to cast another float2 (for the x & y math operations), and you leverage .xy per-component math which is faster then doing it each separately.

In your pixel shader...

float3 processedSpecular = pow(saturate(dot(normal, halfway)), materialPower) * specular;

... HLSL has an intrinsic function called "lit" that you can read more about here... http://developer.download.nvidia.com/cg/lit.html

Basically you hand it a sun luminence dot (NDotL ... dot ( normal, light)), a specular reflection dot (NDotH ... dot ( normal, halfway)) and a specular pow value (your materialPower) it does all the pow, saturate, etc.. basically creates your float specular luminence to * by your float3 specularLightIntensity.

While you still have to calculate the dots in the shader, you'd use the lit function, b/c it replaces the pow,saturate,etc you have with a built-in function doing it more efficiently then you coding it in the shader yourself.

I would also change this stuff around...

float alphaChannel = texColor.a + filterColor.a;

float4 color = 1.2f * (texColor + filterColor.a * filterColor   + float4(processedSpecular, 0.0f));

return float4(color.r, color.g, color.b, filterColor.a + texColor.a);

... you're not using alphaChannel; you're adding filterColor.a + texColor.a in the return again.. so just make your return be...

float4 color;
       color.rgb = 1.2f * (texColor.rgb + filterColor.a * filterColor.rgb   + processedSpecular);
       color.a = texColor.a + filterColor.a;

return color;

... that way you declare 1 float4 return value, and do the math for .rgb and .a separately. B/c as you're doing it in your initial way, you're wasting calculations a) generating a float alphaChannel var that never gets used, b) calculating color.rgba when you just replace color.a in the return anyways (by re-calculating alphaChannel), c) you're casting another float4 in your return, and inefficiently comma-delim'ing your color.r, color.g, color.b values when you can just color.rgb them together.

The idea is to reduce the number of variables casts you make... so while you can "float4 ( somevalue.r, somevalue.g, somevalue.b, somevalue.a )"... if you're already creating a return value, then just use it as the return value instead of recasting it.

Sometimes your return value you're dealing with may just be a float3, eg: if you're only pulling the rgb of a texture, working with it, and the alpha .a will always be 1. Even then.. just cast a float4 from the start, do all your work with the .rgb float3 parts of it, and then set the .a part of it to 1 and return it...

eg:

float4 color;
       color.a = 1;
       color.rgb = tex2d (sample, uv).rgb;
       color.rgb = (complex code that alters it)
       ... ... ...
return color;

You create a single float4, and then just work with it's .rgb through the shader, but return the float4 whole at the end.

You can do this in other places, too... often people will pack HLSL vars full.. eg: they'll take 2 float4's and use the .rgb parts for colors and then pack a float2 in the .a alphas of them...

eg:

struct someObject
{
    float4 sunU; // .rgb = sun vec * light matrix // .a = UV.x
    float4 skyV; // .rgb = sky vec * light matrix // .a = UV.y
}

void vertex_shader ( in blah i, out someObject o)
{
    o.sunU.rgb = suncolor.rgb;
    o.sunU.a = uv.x;
    o.skyV.rgb = skycolor.rgb;
    o.skyV.a = uv.y;
}

I prefer casting a variable once, and then loading it like I did above. But, I see folks double-casting vars all the time, like so...

o.sunU = float4 ( suncolor.rgb, uv.x );
o.skyV = float4 ( skycolor.rgb, uv.y );

.. I mean... it does the same thing: loads the float4's with their values. But, it casts a second float4 on the right-side of the equation to do so. We're casting 4 float4's there.. the sunU and skyV, and then the right-side equations to piece together what we're packing in them. The way I wrote it eariler, you only cast 2 float4's in the struct, then use swizzling to tell them what goes in what parts without having to cast more vars to do so en-masse.

It seems like such a minor thing, and overall it probably is, but when you have something like that in a pixel shader firing off for every pixel... it's just unnecessary overhead ... X many pixels times Y number of frames per second... it adds up.


If the property name has spaces or special characters, there is no need to quote it (and it looks more clear):

var obj = {
    preset_a: {
        input: {
            field_a: "value",
            field_b: "value",
        }
        "i need quotes": "value"
    }
}

I tried to improve the function a little bit. I did it on the fly so i'm pretty sure that something could be wrong. Check it out:

function applyPresets(preset){
    // as Quill said, the return(s) statement has more sense at the top of the method
    if( typeof obj[preset] == 'undefined' ){
        alert('Preset [ ' + preset + ' ] not found!');
        return;
    }
    for( var i in obj[preset] ){
        if( obj[preset].hasOwnProperty(i) ) { // .hasOwnProperty() can be used to determine whether an object has the specified property as a direct property of that object, very useful here
            $.each(obj[preset][i], function(k, v){ // since the code seems very similar we can improve it avoiding more loops
                if( i == 'radio' ){ // if the code below doesn't match, we will need this `if`
                    $('fieldset#' + k + ' > input[type="radio"]').val(v);
                }
                else $(i + '#' + k).val(v); // while they match we don't need more code
            });
        }
    }
    submitSettings();
}

In summary: We use an in loop through the obj[preset] object. This gives us the name of i, so we can easily discard undefined(s) thanks to the .hasOwnProperty() method. The last step is avoid the loops. The syntax is quite the same so we can work inside only one .each() loop. If the selector changes we can always use the lovely if statement.

I made a jsFiddle with the code if you want to see it clearly.


You could look at it in a different way, transform the wall of bricks to a wall of edges, in your example it would be

1, 3, 5
3, 4
1, 4
2
3, 4
1, 4, 5

The first, the third and the last row have an edge at 1, thus you can draw a line that crosses three bricks less than the height of the wall.
You need to find the edge that appears the most.

In this case it would be four it appears in rows 2,3,5,6.

After transforming the wall to a wall of edges, a SelectMany into a GroupBy and Max will do the trick.


Infix to postfix notation in Haskell (Shunting-yard algorithm)

main :: IO ()
main = do
  line <- getLine
  putStrLn $ case traverse str2tok $ splitTok line of
    Left s -> s
    Right ts -> unwords $ map tok2str $ shuntYard ts

-- shuntYard (Token Buffer) = new Token Queue
shuntYard :: [Token] -> [Token]
shuntYard ts = concat queue ++ stack where
  (queue, stack) = (`runState` []) $ for ts $ state . \case
    TNum t -> ([TNum t],)
    TOp LBrace -> ([],) . (LBrace :)
    TOp RBrace -> (map TOp *** drop 1) . break (==LBrace)
    TOp t -> (map TOp *** (t:)) . span (\op -> precedence op > precedence t && op /= LBrace)

Or perhaps:

(queue, stack) = (`runState` []) $ for ts $ \case
  TNum t -> return [TNum t]
  TOp LBrace -> [] <$ modify (LBrace:)
  TOp RBrace -> do
    sstart <- state $ break (==LBrace)
    modify (drop 1)
    return $ map TOp sstart
  TOp t -> do
    ssops <- state $ span $ \op -> precedence op > precedence t && op /= LBrace
    modify (t:)
    return $ map TOp ssops


Iterator-Pattern for an iterator that returns one objects that changes

I think most people would be surprised and annoyed by an iterator that mutated previously yielded values every time you called next. While it makes sense to take what you can from the concept of an iterator, the thing you're trying to make isn't an iterator. (Perhaps the idea of a "cursor" would be more applicable, IDK.)

Your proposed interface {hasCurrent, getCurrent, generateNext} seems fine. I do have some questions/suggestions.

If not x.hasCurrent(), does x.getCurrent() return null, or throw an exception, or what?
Depending on 1 (particularly if it doesn't throw an exception), .getCurrent() sounds more like a read-only property, in which case just call it .current(). (or maybe even just .value)
.generateNext() specifically doesn't make anything (because we're supposing that would be expensive); it changes the thing in question. Therefore maybe call it .mutate() or .becomeNext()
A void return is usually a wasted opportunity, even if just for a little extra debugging context. Exactly what will be best to return here depends on exactly how this is going to be used. Returning boolean success might save you a call to .hasNext(); returning T might save you a call to .current(). Probably boolean is better, but it's hard to say.


The question and the subject is interesting. Recently I needed to make some similar processing; this question pushed me to proceed.

Review

First of all, some remarks about the original implementation.

The method logDuplicates(Path), according to what I see, does not log duplicates, but saves into mongodb all ImageEntry objects corresponding to all image files found in the path. So, to trace duplicates, it is still necessary to execute a couple of requests in mongodb.

There is some room for improvements in this method. Calling datastore.save(imageEntry) for each item separately looked rather suspicious. Doing it in batch mode for all available items should make the thing quicker. Indeed, Datastore.save is overloaded with save(Iterable<T>) and save(T... entities). A slightly improved version of the method would look like this:

private void digestImages(Path path) throws IOException {
  List<ImageEntry> images = new ArrayList<>(APPROX_IMAGES_COUNT);
  Files.walk(path)
       .parallel()
       .filter(Files::isReadable)
       .filter(Files::isRegularFile)
       .forEach(filePath -> {
         if (isImage(filePath)) {
             ImageEntry img = digestAndBuildImageEntry(filePath);
             if (img != null) {
               images.add(img);
             } else {
               System.out.println(String.format("Failed to digest image: %1$s", filePath));
             }
         }});
  datastore.save(images);
}

private boolean isImage(Path path) {
  try {
    String contentType = Files.probeContentType(path);
    return contentType != null && contentType.startsWith("image");
  } catch (IOException ex) {
    ex.printStackTrace();
    return false;
  }
}

private ImageEntry digestAndBuildImageEntry(Path filePath) {
  try (InputStream is = Files.newInputStream(filePath);
       BufferedInputStream buffered = new BufferedInputStream(is)) {
    String hash = DigestUtils.md5Hex(buffered);
    return new ImageEntry(filePath.toAbsolutePath().toString(), hash);
  } catch (IOException ex) {
    ex.printStackTrace();
    return null;
  }
}

Tests

I've got a folder with about 900 JPG image files in numerous sub-folders that I used for tests. Introducing a try-with-resources + batch saving seemed to improve the overall performance for about 10% (see results below).

Based on this SO post that helped me recall different ways and APIs to produce checksums and hashes, I executed a few tests to compare the perfs with the reviewed implementation, as well as when using Guava. The averages of 5 runs on my old i7 gave the following results:

impl               avg time,ms    %
-------------------------------------
original              6583      100.0
reviewed              5873       89.2
guava/sha1            8267      125.6
guava/md5             5865       89.1
guava/murmur3-128     3819       58.0
guava/murmur3-32      2689       40.9
guava/adler32         2432       36.9
-------------------------------------

For the tests with Guava, I used the following overloading of digestAndBuildImageEntry:

private ImageEntry digestAndBuildImageEntry(Path filePath, HashFunction hashFunc) {
  try {
    String hash = com.google.common.io.Files.hash(filePath.toFile(), hashFunc).toString();
    return new ImageEntry(filePath.toAbsolutePath().toString(), hash);
  } catch (IOException ex) {
    ex.printStackTrace();
    return null;
  }
}

So, we can see that, at least for my test case and without entering into theoretical discussions, Guava's adler32 hash performs almost three times faster than the original implementation.


Code comments:

The parameter to the function should be const - "const correctness".
Don't use the variable name "buf" for a variable that is not a memory buffer of some sort.
You have 3 different ways of checking for spaces in your code, you need to check for them in a consistent manner. Either use !isgraph which is the same as checking for ' '. Or isblank, which is the same as checking for ' '  and '\t'. Or possibly isspace, which checks for any form of white space character. I'll use isblank in my suggestion, since I don't know the nature of the string input.
Your code is a bit hard to follow, with several nested loops and if statements.

When I spontaneously rewrite your code to improve readability, I end up with this:

#include <ctype.h>

static int countWords (const char* str)
{
  int count = 0;

  while (*str != '\0')
  {
    while (*str != '\0' && isblank(*str)) // remove all spaces between words
    {
      str++;
    }
    if(*str != '\0')
    {
      count++;
    }

    while (*str != '\0' && !isblank(*str)) // loop past the found word
    {
      str++;
    }
  }

  return count;
}

This code is very easy to understand. However, you asked for optimization and my code doesn't look all that effective; it is possibly slower than the original. Particularly, we have multiple checks for '\0' all over the place.

Note that any truly meaningful optimization requires that 1) we have actually encountered and measured a real performance problem, 2) we have noticed that the compiler is doing a poor job at optimizing that particular problematic code, and 3) we have fairly good knowledge of the target CPU and hardware. It a bad idea to manually optimize code if those 3 above conditions are not met.

Still, I'll attempt a manual optimization of this, since it was requested. It may or may not be more effective. Branch prediction may be a more serious concern than the number of comparisons executed, for example. For what it is worth, here you go:

#include <ctype.h>
#include <stdbool.h>

static inline int countWords (const char* str)
{
  int count = 0;
  bool look_for_data = true;

  while (*str != '\0')
  {
    if( (look_for_data ^ isblank(*str)) != 0) // is it a character of interest?
    {
      count += (int)look_for_data; // increase count if we are looking for data
      look_for_data = !look_for_data;
    }
    str++;
  }

  return count;
}

With this optimization we have managed to reduce the number of instructions and the number of branches both. But as you can tell, the code now turned quite obscure.

Explanation:
The fundament of this code is that one lap in the loop corresponds to one character in the input string. The bool variable keeps track of whether the code is currently looking for spaces or non-spaces.

We are only interested in the places in the string where we go from looking for spaces to looking for data, or vice versa. When that happens, we should start looking for data if we were looking for spaces, and the other way around. Also, in the case where we go from spaces to data, we should increase the word counter.

The boolean logic truth table is:

look_for_data  isblank  of interest  comment
false          false    false        we are at symbols and found another symbol
false          true     true         we are at symbols and found a space
true           true     false        we are at spaces and found another space
true           false    true         we are at spaces and found a symbol

We can see that this happens to be the truth table for logical XOR.


As others have mentioned, you are attempting to find the digital sum of a given number. In JavaScript, you can do the following:

function digitalSum(number) {
  return (
    number
      .toString()
      .split('')
      .map(c => parseInt(c))
      .reduce((a, b) => a + b)
  )
}

As it intuitively appears, the code above does the following:

convert the number into a string
split the string by the empty string, thus each digit/character of the string is an individual element of the new list
converts each digit from a string to an actual number
Reduces the list by the sum function

There are other ways of accomplishing this task, but I believe the above is rather easy to understand.


AngularJS controller to fetch and display employee data from database

You should create a json object for your errors. Key - error number, value - custom error message. Try to be DRY. Just imagine situation, when i18n will be required.


You shouldn't need to post (or even have) two versions of the same source code. You should only have one readable version, and use a compressor to create a production version.

And IMO it would be fine to use method chaining in the second (readable) version.

Concerning your question: I think the whole code is fine as it is. I'll list some points that one may differently in the second block, but I don't believe they are really needed:

You could avoid the || {} by validating the options first, or before calling this method, or simply not allow the queries property to be undefined.

You could use an arrow function (if your target systems support it, or by using a ES6 compiler):

form.append($.map(options.queries, (name, value) =>
  $("<input>").attr({
    "name": name,
    "value": value,
    "hidden": true
  })[0]
));

And you could use the native JavaScript and more light weight Array.map() method:

form.append(Object.keys(options.queries).map((key, index) =>
  $("<input>").attr({
    "name": key,
    "value": options.queries[key],
    "hidden": true
  })[0]
));

Expanding on the last point: Now-a-days it's worth considering, if you still need jQuery at all. It was once a big help to bridge incompatibilities between browsers, but current browsers almost compatible to each other.

EDIT: Here's a version without jQuery:

function redirect(options) {
    let form = document.createElement("form");
    form.setAttribute("hidden", "");
    form.setAttribute("action", options.url);
    form.setAttribute("target", (options.new_tab === true) ? "_blank" : "_self");

    Object.entries(options.queries || {}).forEach(([name, value]) => {
        let input = document.createElement("input");
        input.setAttribute("hidden", "");
        input.setAttribute("name", name);
        input.setAttribute("value", value);
        form.appendChild(input);
    });

    document.body.appendChild(form);
    form.submit();
}


I would use a for loop instead of recursive calls:

protected function _hashPassword($password = NULL, $rounds = 1000) {
    if (!isset($password)) throw new Exception('No password set!');

    $salt   = 'K^^%/m>(|{z= $1^>%>W[=4U5*p|,E';
    $pepper = '08[)^,&%^^771^=>&,E[XP::4})h*I';

    $dinner = $salt . $password . $pepper;

    for ($i = 0; $i < $rounds; $i++) {
        $dinner = sha1($dinner . $password);
    }
    return $dinner;
}

From http://php.net/manual/en/functions.user-defined.php:

  It is possible to call recursive functions in PHP. However avoid
  recursive function/method calls with over 100-200 recursion levels as
  it can smash the stack and cause a termination of the current script.

Furthermore, I would use the username as 'pepper'. It would make your hash more unpredictable.