Opening a list of URLs and splitting the queries into different files

Before We Get Started

It would be good if you could provide some examples of the URLs that you are looking to parse, I did a cursory search and I couldn't coerce a query result from any that I tried with:

urlparse.parse_qsl(urlparse.urlparse("some_url").query

In the interest of brevity I'll assume you have some set of URLs that this is working for.

Code Review

Step one in making your code more generic will be to remove the hard-coded URL text file from your function body. I would suggest it be a parameter to the parse_file function.

Also, You don't need to do this:

lines = infile.readlines()
for line in lines:

.readlines() isn't necessary in how it is being used here and the file can be read without it. You obviously know about the With Statement and how to use it as a context manager - but you're still opening and closing your URL list file manually!

infile = open("URLlist.txt", 'r')
...
infile.close()

Instead, you can alias the opened file in your With Statement and it will be iterable without .readlines():

with open(input_file) as input:
    for line in input:

Also, if you find yourself using multiple If/Elif clauses you might consider it time to look into some of Python's more interesting data structures, below I'm using a dictionary.
You can replace your predicate:

if k == 'blog':

and instead use a key in a dictionary with the value corresponding to the the subsequent procedure.

{'blog' : "blog_file.txt"}

Revision

Below is a possible revision to your code:

import urlparse
def parse_file(input_file):
    tags = {'blog' : "blog_file.txt",
            'p' : "p_file.txt",
            'attachment_id' : "attachment_id_file.txt",
            'lang' : "lang_file.txt",
            'portfolio' : "portfolio_file.txt",
            'page_id' : "page_id_file.txt",
            'comments_popup' : "comments_popup_file.txt",
            'iframe' : "iframe_file.txt",
            'width' : "width_file.txt",
            'height' : "height_file.txt"}
    with open(input_file) as input:
        for line in input:
            parsed_url = urlparse.parse_qsl(urlparse.urlparse(line).query)
            if len(parsed_url) > 0:
                for key, value in parsed_url:
                    if key in tags:
                        with open(tags[key], 'a') as output_file:
                            output_file.write(value)
                    else:
                        print key + " not in tags."
            else:
                print(line + " does not yield query.")

I think this should work as you describe, but without a set of example URLs it's difficult to say for sure. The line:

if len(parsed_url) > 0:

is used here because I couldn't coerce .query to return anything but an empty list on those URLs I attempted.

Final Thought

It might be a good idea to change the functionality for those keys not found in your tags dictionary. You might consider creating a miscellaneous, or catch-all file that unmatched values get written to. That way you don't totally lose work on those unmatched URLs.

This is all based on the assumption that you have some domain that your code is currently working for.


Time consumption suggestions

Doing list(Image.open(filename).getdata()) means that you read the entire image before starting any processing. This means time and memory overhead in the order of number of pixels. It looks like you only ever need to process one pixel at a time, so you can instead iterate over the results of getdata() directly, treating the pixels as a stream. This becomes crucial when dealing with even bigger data structures, especially when the full data won't fit in memory. If the result of getdata() is not the best for your purposes there are many other ways of iterating over pixels in an image. Iterating over the text data is probably less crucial (since the data should be much smaller), but would also improve matters over reading the entire thing at once.

You are currently doing many value conversions, from UTF-8 string to binary and back, binary to int and back, and pixel to list (presumably to separate colour values). Avoiding these conversions should massively improve the speed of your program. In general, settling on a single "datatype of exchange" is a good idea, and in this case integers are an obvious choice - they map easily to both text and pixel values, and they are blazingly fast to work with.

General suggestions

You have optional parameters which are never used with anything other than their default values. This adds clutter, and makes me suspicious of whether the functions would even do the right thing if called with anything else.

Use argparse to allow specifying the input data file and image file. This makes the program much more versatile and acceptance testable.

Test driving this code should point towards some limitations of this program:

What if the data doesn't fit in memory?
What if the image is too small to encode the entire text?
What if the user specifies bits > 8?
Why assume UTF-8 rather than just encoding arbitrary byte values? The extra limitation of UTF-8 makes it harder to ensure that the data is correctly encoded and decoded, and limits the utility of the program. You might for example want to encode an image within another image.
What if the image is not eight bits per pixel?
What is the maximum perceptive colour distance between an unmodified and a steganographic pixel? That is, could a person possibly detect the colour difference, for example in a high quality photo with big uniform patches or a uniformly coloured generated picture?

pep8 is a great little tool to ensure your code is idiomatic Python. For example: in Python variable names are always under_scored by convention.


I see a number of things which may help you improve your code.

Don't abuse using namespace std

Especially in a very simple program like this, there's little reason to use that line.  Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Don't reseed the random number generator more than once

The program currently calls srand at the top of each call to getCard(), but this is really neither necessary nor advisable.  Instead, just call it once when the program begins and then continue to use rand() to get random numbers.  Better yet, use the next suggestion.

Consider using a better random number generator

You are currently using

int cardsuit = rand()%4;

There are two problems with this approach. One is that the low order bits of the random number generator are not particularly random, so neither with cardsuit be.  On my machine, there's a slight but measurable bias toward 0 with that.  The second problem is that it's not thread safe because rand stores hidden state.  A better solution, if your compiler and library supports it, would be to use the C++11 `std::uniform_int_distribution.  It looks complex, but it's actually pretty easy to use.

Eliminate global variables where practical

Having routines dependent on global variables makes it that much more difficult to understand the logic and introduces many opportunities for error.  Eliminating global variables where practical is always a good idea, whether programming for desktop machines or for embedded systems.  For global variables such as drawnCards and `numberOfCardsDrawn, consider wrapping them in objects to more easily keep them synchronized.

Use object-oriented programming

The game is written much more in the procedural style of C rather than in the object-oriented style of C++.  The cards and the deck could each be an object, with most of the procedures as functions of those objects.  This would reduce coupling and make the program easier to understand.

Eliminate "magic numbers"

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

Use const where practical

In your isMyCardAlreadyDrwan routine, the passed card is never altered, which is just as it should be.  You should indicate that fact by declaring it like this:

bool isMyCardAlreadyDrawn (const std::string& card)


A thing of beauty
For such an odd/complicated logic, you certainly have made your code easy to follow along. Your comments are succinct and well used to label the CTEs.
Your CTE names are perfect for the code to read fluidly. The spacing and indentation is both useful and consistent. You certainly know how to write some SQL.

Small nitpick
I feel that the table aliases are not the best, and perhaps not even needed, since the table names on SEDE are not particularly long and they are quite descriptive. i especially gave me pause.
from  CandidateEdits as ce
inner join FirstEdit as i on ce.EditId = i.EditId
inner join Revisions as r on ce.EditId = r.EditId


About Constructor

It is considered a bad practice for a constructor to have side effects for multiple reasons. You can browse numerous resources online on this subject. Here are a few whys:

The reader/maintainer of the code does not expect a constructor to have any side effects;
Such constructor is hard or impossible to test;
It violates a whole bunch of principles, including Principle of least astonishment, SRP.

So, yeah instead of

constructor(htmlObject,parent, position){
  // ...
  this.init();
}

you should rather create an instance and invoke the init() on it; like this

const draggableElement = new Mover(
  document.querySelector('.dragable'),
  document.querySelector('body'),
  'absolute',
);
draggableElement.init();

If you are not planning to add the function that disables "moving" of an element, you may even not need a local variable holding the reference to a Mover:

new Mover(
  document.querySelector('.dragable'),
  document.querySelector('body'),
  'absolute',
)
.init();

Naming Things

Naming is important. Method init() is not informative. You may want to rename it to something like enableElementDragging(). A symmetric counter part is now too easy too name – disableElementDragging().

Nano variable names are evil. What is e? An error? An exception? An event? To figure that out I need to look at a place where the function is being invoked. That's mental burden.

Same applies to pos, w, and h... If you are in VS Code or any other smart editor, it's a matter of hitting F2 and renaming it.

Names mx and mh are particularly unfortunate since they are meant to be symmetric to/consistent with w and h. Thus, mx should be mw! Also, I could not decipher what the m prefix means in both of these variables.

Just spell things out: position, width, height, parentWidth, parentHeight, calculatePosition().


Split data from single CSV file into several CSV files by column value

Don't use string literals as comments. PEP 8 explains how to use comments.
Docstrings should use """ rather than ''', as described in PEP 257. Also your docstring doesn't need the "-", and should probably be rephrased slightly to fit on one line.
Close files, #fb.close() shows you went out of your way to make bad code. Without fb.close or wrapping open in a with, the file is not guaranteed to be closed. I personally prefer with to fb.close, as described here.
Personally, rather than over-riding your files \$n\$ times, I'd use collections.defaultdict, to group all your files into their rows.
You may want to change get_file_path, to be based of __file__. Or leave your path to be relative, as it'll default to that behavior.

import os
import csv
from collections import defaultdict

FILE_DIR = os.path.dirname(os.path.abspath(__file__))

def get_file_path(filename):
    return os.path.join(FILE_DIR, filename)

file_path = get_file_path('argos.csv')
with open(file_path, 'rU') as csvfile:
    reader = csv.reader(csvfile)
    header = next(reader)
    data = defaultdict(lambda:[header])
    _ = data[header[5][:5]]
    for row in reader:
        data[row[5][:5]].append(row)
    for file_name, rows in data.items():
        with open(file_name, 'w+') as f:
            for row in rows:
                f.write(str(row) + '\n')


Improving the running time of finding the count of pairs satisfying a symmetric relation

You are going in wrong direction. Entertaining the symmetry doesn't change the quadratic nature of the algorithm (using floating point in a seemingly number-theoretical problem also raises a red flag). The correct approach involves some math.

We are interested in integers \$a,b,n\$ satisfying the relation

$$\sqrt[3]{a} + \sqrt[3]{b} = \sqrt[3]{n}$$

Notice that if \$a\$ and \$b\$ have a common factor, \$n\$ necessarily has the same factor, so we are primarily interested in the solutions with \$a\$ and \$b\$ coprime.

We are going to show that such nontrivial solution is only possible if \$a\$ and \$b\$ are perfect cubes.

Now, \$(\sqrt[3]{a} + \sqrt[3]{b})^3 = n\$. Expanding the binomial gives $$3\sqrt[3]{ab}(\sqrt[3]{a} + \sqrt[3]{b}) = n - (a + b)$$

that is,

$$3\sqrt[3]{nab} = n - (a + b)$$

Since the RHS is obviously integer, so must be LHS. Assuming that \$a\$ is not a perfect cube, it must have some prime factor \$p\$ in a non-cubic power. Further assuming that \$b\$ is coprime to \$a\$, the remaining powers of \$p\$ must be supplied by \$n\$, that is \$n\$ is also divisible by \$p\$.

It means that LHS is divisible by \$p\$, and since \$b = n - a - 3\sqrt[3]{nab}\$, it follows that \$b\$ is also divisible by \$p\$, which contradicts the assumption.

We proved that the set of solutions is comprised by pairs of

$$A = x^3 z, B = y^3 z$$

with \$x, y\$ being coprime integers, and \$z\$ being an arbitrary integer. Enumerating such pairs shall not be a problem.


Run control tasks asynchronously using TPL

First, some notes about your code:

Using Tasks that are first created and later started usually doesn't make much sense. To represent some work to be done, just use a delegate.
Tasks almost never need to be Disposed.

Now, I think that what you want to do would be easiest to achieve using ActionBlock from TPL Dataflow. When you want to perform the operation, you would send a message to the block and the action in the block would execute it. ActionBlock already performs all synchronization necessary to make sure only one operation executes at a time.

ActionBlock<bool> _changeControlBlock = new ActionBlock<bool>(ChangeControl);

private void ChangeControl(bool on)
{
    if (on)
    {
        // turn on
    }
    else
    {
        // turn off
    }
}

public void TurnOn()
{
    _changeControlBlock.Post(true);
}

public void TurnOn()
{
    _changeControlBlock.Post(false);
}


There are two ways to tackle this situation. One of them is what you did: follow the Law of Demeter; I don't have any advice to improve your code. The second way is move the logic to the other model. In that case you'd write:

class Company
  has_many :accreditations
end

class Accreditation
  scope :departments, where(kind_cd: department)

  def self.legal
    where(kind_cd: legal).first
  end
end

Both are ok even though I prefer the second because the logic of departments/legal is within the accreditation model.


jQuery dropdown plugin to prevent scanning the whole DOM on every click

Comments:

Don't use the name 'dropdown' that has a very high probability for naming collisions with other libraries.
I get that you might want to do stuff as a learning experience but you are recreating something that already exists (as a matter of fact a lot of versions of this widget exist). You might want to check out how something like chosen works.
In a similar vein, this ain't gonna work with keyboard input. Maybe you don't need it, but people would expect a dropdown widget to work with keyboard input
This seems to require that a certain html structure exists. Someone using this without that knowledge will get confusing and silent failures. The way that jquery ui widgets usually handle this is to hide the initial element and then use jquery.after() to create the expected elements right after it
Actually you really should use the jquery ui widget factory that is a better fit for this then just a bare jquery plugin. (Jquery plugins generally are better for adding behaviors, JqueryUi Widget Factory is the preferred way to create enhanced controls)
Are you sure you want to only close dropdowns on a click event? That seems far too simplistic. What if someone opens your dropdown and uses the tab key to tab to other fields? Usually something like this will close when focus is lost (I believe that is the blur event)
I'm not sure if everything is a child of the html element - detached pop-up dialogs made via jquery ui for example. (not sure about this one)
You do not need to stop propogation nor clearMenus when the toggle is clicked. The click will propagate up to the html element and close it then.
You will bind the clearDrops function to the html element's click event as many times as there are controls on the page - you only need it once. Do a check or unbind.
Is scanning the whole DOM really a problem? The scan only happens when the user interacts with the page, she will have to click on things very quickly indeed for this to be a real preformance problem.

A direct answer to your question: Just remember what dropdown controls have been initialized and hide those.

( function($) {
    var initializedDropdowns = $();

    $.fn.dropdown = function () {

            return this.each(function () {

                var $this = $(this),

                ...
                initializedDropdowns.add($this)
                ...
                var clearDrops = function () {
                    initializedDropdowns.hide();
                };
                ...
            });

        };
} )(jQuery)


TextView vs Button for Android AlertDialog

Answer is Button.

Button is a subclass of TextView. So it has all the features of TextView and additional features of Button class. Button adds a few stylistic changes (e.g., default background image, additional padding, ripple effect) to allow quicker adaptation to your designs.


Here is suggestions. Every approach has pros/cons, depending your app architecture and model complexity.
class MyResponseModel {
  // I think values in response model should be let instead of var
  // By definition response model should be immutable
  let question: String
  let id: String
  let answer: String

  // I guess MyResponseModel will be initialized from JSON and you can just conform it to Codable
  // Then you don't need this init(from dictionary: [String: Any])
  init(from dictionary: [String: Any]) {
    self.question = (dictionary["question"] as? String) ?? ""
    self.id = (dictionary["id"] as? String) ?? ""
    self.answer = (dictionary["answer"] as? String) ?? ""
  }
}

struct MyTableCellViewModel {
  // I'm not sure what logic do you have, but I think it is better to define properties using let instead of var
  let title: String
  let detail: String
  let isSelected: Bool

  init(title: String, detail: String, isSelected: Bool) {
    self.title = title
    self.detail = detail
    self.isSelected = isSelected
  }

  // Approach #1: create initializer from necessary response model
  init(responseModel: MyResponseModel, isSelected: Bool) {
    self.init(title: responseModel.question, detail: responseModel.answer, isSelected: isSelected)
  }
}

// Approach #2: create separate mapper class (useful when you need to have external dependencies in order to map
// For example you need to add some info that is not relevant to MyResponseModel.
// Let's take cell selection info as an example

protocol MyTableCellSelectionProvider {
  func isCellSelected(for responseModel: MyResponseModel) -> Bool
}

struct MyTableCellViewModelMapper {
  let cellSelectionProvider: MyTableCellSelectionProvider

  func map(responseModel: MyResponseModel) -> MyTableCellViewModel {
    return MyTableCellViewModel(
      title: responseModel.question,
      detail: responseModel.answer,
      isSelected: cellSelectionProvider.isCellSelected(for: responseModel)
    )
  }
}

// Approach #3: define cell view model protocol

protocol MyCellViewModel {
  var title: String { get }
  var detail: String { get }
}

extension MyResponseModel: MyCellViewModel {
  var title: String { return question }
  var detail: String { return answer }
}


Formatting & Conventions
Always run your code through an autoformatter. On Linux, I use clang-format, and on Win10 I use VSCode's autoformatting intellisense features. I'm not sure of your exact setup, but formatting is big.
Next, variable names. The variable choose is wonderfully descriptive. I know immediately what it's for. The variable P_h on the other hand is vague and undescriptive. Don't worry about how long your variable names are. The compiler won't care. Instead focus on making variable names that are descriptive, like Player_health so that anyone who reads your code immediately understands it.
Program Flow
Ignoring all the messy specifics, this is what I read your program's flow as:
while playing:
    setup variables.
    get player input
    if player doesn't want to play
        exit
    otherwise:
        main game loop
    if lose:
        ask to replay
    if win:
        ask to replay

I'm purposefully ignoring the main game loop for now. Right off the bat, I see one big problem: You do the same thing twice down at the bottom. That whole choose==0 thing can be moved outside the if statements because in either case, you'll encounter it. (In the case where E_h>0 && P_h>0, you won't have exited the main game loop, so we can ignore that.)
That would look like this:
if (E_h <= 0) {
    puts("You killed the enemy!\nWould you like to play again? [0 to exit, Press anything else to play again]");
}
else if (P_h <= 0) {
    puts("You died. Would you like to play again to try to defeat the enemy. [0 to exit, anything else to play again]");
}
scanf("%d", &choose);
if (choose == 0) {
    play = false;
    break;
}
else {
    play = true;
}

Even here, we can optimize further. Watching program flow, anytime we hit the scanf on this code, we can assert that play==true and so we can remove the whole section that sets it. Furthermore, since the very next thing we do is run while (play) we can cut out the break, since it'll exit the loop naturally. Finally, conditionals that only run a single statement don't need brackets. (That one's up to personal choice, and doesn't really affect your code. I like to knock them off of there.) Thus, we can take 25 lines of code down to
if (E_h <= 0)
    puts("You killed the enemy!\nWould you like to play again? [0 to exit, Press anything else to play again]");
else if (P_h <= 0)
    puts("You died. Would you like to play again to try to defeat the enemy. [0 to exit, anything else to play again]");
scanf("%d", &choose);
if (choose == 0)
    play = false;

just seven.

Next, let's look at the part of the code where you initially ask if the player wants to play. Logically, if the player runs your code, you can assume that they meant to. The whole initial choice section can be removed. (If you choose to leave it in there, think about what might happen if the player decides to replay the game. Right now, they have to say they want to (re)play the game twice!)
Main Game Loop
Ok, here's the meat of it. First thing you can do is move this little number to the end:
if (P_h <= 0) {
    puts("You have died");
    break;
}
if (E_h <= 0) {
    puts("you win!");
    break;
}

and remove the second break. That functions the same, but you don't have to calculate attack values for a round you're not going to use.
As for your actual 'attack' section, it looks like you can significantly reduce that as well. You've got two options here: Either use switch statements or modify the program flow. switch would look like:
switch at_p
{
    case 0:
        super_attack code;
    break;
    case 1:
        regular_attack code;
    break;
    default:
        idiot_code;
}

As for program flow: Notice that in both of the attacks, you have very similar/identical code.  If you code for the boundary conditions right, imagine what you could do with P_at = SP. You could significantly refactor your main loop.
I'd personally go for the switch statement simply because it's more amenable to future upgrades.
Other suggestions
Don't use stdbool.h. It's a lot easier to operate using int. Generally, false maps to 0 and true maps to anything that isn't false. (Plus, ints are normally 4 bytes big and bools are 1 byte big. You've got gigs of space to use.) I never use bools, and if I need to use them, I'll declare a union and make a utility variable that holds boolean flags.
Watch for program flow. A good maxim to work towards is having only one return location. Whether that's return, break, exit() or continue, minimizing the number of ways a program can escape a particular section of code makes it easier to debug. Oftentimes you can move things at the beginning of loops to the end, negate the conditional inside of an if statement, or otherwise simplify your code just by jimmying around with it a bit.
Keep track of variable's possible values throughout your code. If something has to be a certain value at a particular point in the code, then there's no point checking that value or setting it to what it already is. This can get a little more complicated with bigger code, but it's a powerful skill.
Suggestions for future features
Perhaps look at implementing some more options in the main game, such as

defending and armor
quitting from within the main game loop
breaking the attack/defend portions out into their own functions

Also take a look at

do-while loops
Switch statements
constants

All in all, your code is good, but there's a few modifications to program flow that can be made to cut down on operational complexity.


A couple of simple things I notice right off the bat.

If you have a method which only calls another method, why bother having the first method at all?  I'm personally against these one-line wrapper methods and see them as unnecessary noise.
Your methods should be verb phrases, in general (e.g., CollisionHelper.helpCollision or even performCollision, in this case, since it's doing all of your processing).
I believe there's a standard for replacing instanceof usage with an actual method from the Class API, as follows: BombControl.class.isInstance(event.getObjectA()).  You can see more on this Stack Overflow Q&A.  (Apparently you're using it correctly here, however.)

From the comments: you obviously should move the entire huge method body to the helper method, otherwise you have the same problem.  Just extract 'til you drop.


Efficiently determining maximum allowed euclidean distance between lists of colors

As @vnp says, a solution involving an octree would a more efficient way to find neighboring points.

Before you implement one, though, there are some huge time savings you can get by making some trivial changes:

Computing square roots is computationally intensive.  Do it only when you need to.
Parsing hex values into integers is somewhat slow, especially when you do it using a lot of string and array operations.  It would be more efficient to parse the entire 6-hex-digit string into an integer, then use bit manipulation.
The same goes for generating random colors.  I don't know why you used rand(254) rather than rand(256).  If you allow color components FE and FF, then it becomes a simple matter of generating a 24-bit random number, and formatting it as hex.  (Better yet, avoid converting the colors into their hex representation altogether, and just store them as integers.)

In addition, 1.upto(10000) { color_list << random_color } is poor Ruby style.  Write it using .map instead (like you did in the implementation of random_colors).

I don't know why you wrote results[t] ||= [] instead of results[t] = [].

With just those changes, I'm able to reduce the execution time by 90% already.

def color_dist_sq(c1, c2)
  c1 = c1.to_i(16)
  c2 = c2.to_i(16)
  [0, 8, 16].map do |bits|
    ((c1 >> bits & 0xff) - (c2 >> bits & 0xff)) ** 2
  end.inject(:+)
end

def random_color
  '%06x' % rand(1 << 24)
end

TARGET_DISTANCE_SQ = 10**2
color_list = 10000.times.map { random_color }
target_colors = 100.times.map { random_color }

results = {}
target_colors.each do |t|
  results[t] = color_list.inject([]) do |result, c|
    dist_sq = color_dist_sq(c, t)
    result << [c, Math.sqrt(dist_sq)] if dist_sq <= TARGET_DISTANCE_SQ
    result
  end
end


Handling large images efficiently (to avoid OutOfMemoryError)

This looks like a bug:

while ((halfHeight / inSampleSize) > dstWidth
        && (halfWidth / inSampleSize) > dstWidth) {

You probably meant this way:

while ((halfHeight / inSampleSize) > dstHeight
        && (halfWidth / inSampleSize) > dstWidth) {

In onDestroy you call bitmap1.recycle(). One problem with that is bitmap1 might be null. The bigger problem is that you try to decode 3 bitmaps earlier, and bitmap1 will point to the last one, so you will recycle only the last one, neglecting the first two.

I'm not sure this is necessary at all, and I cannot find the relevant documentation. If it's really necessary to manually recycle all Bitmaps like this, then you need to store the references of all the Bitmaps you decoded, so that you can recycle on in onDestroy.

This looks a bit like magic, though mostly not your fault:

BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;

BitmapFactory.decodeResource(getResources(), R.drawable.image1);
BitmapFactory.decodeResource(getResources(), R.drawable.image2);
BitmapFactory.decodeResource(getResources(), R.drawable.image3);

int srcWidth = o.outWidth;
int srcHeight = o.outHeight;

If I understand the docs correctly, you set o.inJustDecodeBounds = true so that you can run BitmapFactory.decodeResource(...) without allocating memory for images, so that you can query o.outWidth for image dimensions. If indeed such magic is going on, some comments would be nice.

I suspect that if you call BitmapFactory.decodeResource(...) 3 times, o.outWidth will have the width of only the last image. So you might want to rework this, extracting the main processing to a private method, and running it for each image separately.

Also in the docs, if decoding fails, then o.outWidth will be set to -1, and you might want to add some checks to handle that case gracefully.

This pattern is repeated 3 times:

bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.image1, o);
iv1.setImageBitmap(bitmap1);

It would be good to extract this to a private method:

private void setImageBitmap(int viewId, int imageId, BitmapFactory.Options options) {
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageId, options);
    ImageView view = (ImageView) findViewById(viewId);
    view.setImageBitmap(bitmap);
}

Which you can call with:

setImageBitmap(int R.id.iv1, int R.drawable.image1, o);
setImageBitmap(int R.id.iv2, int R.drawable.image2, o);
setImageBitmap(int R.id.iv3, int R.drawable.image3, o);

If indeed you need to recycle the Bitmaps in onDestroy, then the new setImageBitmap helper is a good place to add the decoded Bitmap to a collection.


Determine total number of ways of reaching a destination

Although this is not related to optimization, it looks like you could improve some of the ways you use loops.  If you're using a counter, chances are you should use a for loop:

for (int i = number; i > 0; i--) { /*...*/ }

This works best if the loop counter initialization is pretty short.  But if it's too long and should remain on its own line, then instead have a while loop that updates the counter within the statement:

int i; // some long initialization here instead...

while (i-- > 0) { /*...*/ }

First, I want to mention that you should use whitespace between operators and keywords for readability.  You use it in some places, but you should use it everywhere for consistency.

Second, non-empty code blocks should have the opening curly brace at the end of the line, not on the following line.  This is referenced in Google Java Style.

Instead of decrementing testCases within the loop:

while(testCases!=0)
{
    stationId = Integer.parseInt(br.readLine());
    ways[i++] = (short)(getWays(stationId)%(10^9 +7));
    testCases--;
}

have it done in the while loop statement:

while (testCases-- > 0) {
    stationId = Integer.parseInt(br.readLine());
    ways[i++] = (short)(getWays(stationId)%(10^9 +7));
}

Instead of incrementing i within the loop:

while(i<=n)
{
    sum+=(i-1);
    i++;
}

make it a for loop:

// move the initialization of i into the loop

for (int i = 1; i <= n; i++) {
    sum += (i-1);
}

On another note, this:

short ways[]=new short[testCases],i=0;

should be on separate lines:

short ways[] = new short[testCases];
short i = 0;

Although they're of the same type, i is hard to see since it's crammed right next to ways[].


Increase efficiency for an R simulator of the Monty Hall Puzzle

R has vectorized operators and using those is much more efficient in this case:

Monty_Hall2 <- function(repetitions){
    doors <- c('A','B','C')
    winning_door <- sample(doors, repetitions, replace=TRUE)
    contestant_choose <- sample(doors, repetitions, replace=TRUE)
    stay_wins <- winning_door == contestant_choose
    switch_wins <- winning_door != contestant_choose
    series <- data.frame(sim_num = seq_len(repetitions),
                         cum_sum_stay = cumsum(stay_wins),
                         cum_sum_switch = cumsum(switch_wins))
    plot(series$sim_num,series$cum_sum_switch,col=2,ylab='Cumulative # of wins',
         xlab='Simulation #',main=sprintf('%d Simulations of the Monty Hall Paradox',repetitions),type='l')
    lines(series$sim_num,series$cum_sum_stay,col=4)
    legend('topleft',legend=c('Cumulative wins from switching',
                              'Cumulative wins from staying'),col=c(2,4),lty=1)
    list(series = series,
         stay_wins = series[repetitions,"cum_stay_wins"],
         switch_wins = series[repetitions,"cum_switch_wins"],
         proportion_stay_wins = series[repetitions,"cum_stay_wins"]/repetitions,
         proportion_switch_wins = series[repetitions,"cum_switch_wins"]/repetitions)
}

That is, generate all the answers and guesses, check for each one (vectorized) which (staying or switching) would be a win, and then accumulate those results. The rest is just to put the data in the same format that your function already had.

> system.time(tmp <- Monty_Hall(10000))
   user  system elapsed
   6.04    0.00    6.04
> system.time(tmp <- Monty_Hall2(10000))
   user  system elapsed
   0.01    0.02    0.03

So approximately 1/600 of the time. Or, since I didn't do proper benchmarking, say between 2 and 3 orders of magnitude quicker.


The first small comment is that there's no need to put this extra div tag. Simply apply the page-background id to your img tag. It's still nice that you put it in the HTML code.

The other two issues are image ratio (do you want it to be preserved?) and browser support (willing to support IE6 and old Android and iPhones?)

position: fixed is not supported before iOS 5 and Android 4.0. Doesn't work on IE6 either. You could use a method that has been tested for every desktop browser since IE5 and will also work on any phone (tested on my old Android).
If you want to preserve image ratio and don't care about old desktop browsers, you could use the CSS3 background-size:cover property supported since IE9, Android 2.2 and iOS4.
If you want to preserve image ratio and support every browser, there's the usual JavaScript fallback. Use Modernizr to detect the CSS3 property and this jQuery script to simulate background-size: cover.


There is not much to improve in my opinion, except:
Unnecessary use of std::move()
You are passing shouldLatch, onLatch and onUnlatch by value to the constructor, so there is no reason to use std::move() in the member initializer list.


Improvement of a regular expression pattern

To be honest I don't think your current way of handling is 'clean'.
But I would suggest you to use a HTML DOM parser. I took the liberty to google it for you and http://simplehtmldom.sourceforge.net/ seems quite what you need.

It's a PHP HTML parser, which allows you to write

// Find all element which class=foo
$ret = $html->find('.at-the-moment');

instead of

preg_match_all('/
(.*?)
(.*?)<\/div>/is', $code_page, $channels);

Also your other regexes can be switched (read the documentation)

To be honest, I never used this library before, but I've worked with beautifulsoup which is a Python equivalent, which would do the trick for you perfectly.
(source: http://www.givegoodweb.com/post/210/html-parser-for-php)

Wishing you the best!


Calling Stored Procedure "insert query" using EF 6, UOW, and MVC 5

Your mapping is designed to call a stored procedure when you call context.Applicants.Add() and context.SaveChanges(). Your second code manually calls a stored procedure, that is not what you want to do. Simply keep your mapping:

using(var context = new MyExperienceDbContext())
{
    context.Applicants.Add(entity);
    context.SaveContext();
}

Also this code does not belong in your controller, it belongs in your repository.

public interface IApplicantRepository
{
    void AddApplicant(Applicant applicant);
}

For a more advanced look at Repositories please read the first part of my article: http://www.lind-i.com/Docs/DataSelectorsWithMVVM.pdf


Rendering JSON arrays of unequal length as a table

The first thing I noticed is that the format of the data is a collection of columns with rows. The variable maxNumCols seems mis-leading. A more appropriate name for that variable would be maxNumRows because it describes how many rows are needed.

In terms of reducing the transformations needed, one option to consider is finding the maximum number of rows in a column and using that with v-for _with a Range to determine how many rows to add. Then looping over the content would eliminate the need to create recordArraySchema and dataTable - which would reduce the complexity from \$O(n^2)\$ to just \$O(n)\$.

        {{column[r - 1].row}}

Obviously this would require saving maxNumRows in the data collection.

Instead of using Function.apply() the spread syntax can be used to determine the maximum number of rows.

const rowLengths = data.map(r => r.length);
this.maxNumRows = Math.max(...rowLengths);

And instead of using let for variables that are only assigned once, it is wise to use const and then if it is determined that it needs to be re-assigned, use let. This helps avoid accidental re-assignment.


Reusability vs simplicity in a small game with a set of interfaces

The problem, however, is that this means when creating my classes, I need to ferry around this TPos generic construct to places where it doesn't make sense to define it. I'm left creating new Player<Vector3> or Player<Int2> instances all over the place when really I just want to be creating a Player.

Yes, specifying Player<Vector3> each time can be quite frustrating. I'm not sure though if you just want to create just a Player or if you want to create a specific kind of player

You could create a GameOnePlayer class which extends Player<Vector3>, so then you create a GameOnePlayer and not a Player<Vector3>. You might have use for the Abstract Factory Pattern for the creation of these objects.

I think however that your class inheritance will become quite complex, if it isn't complex enough already. Which you state yourself with this:

  An additional problem is that this might not (conceivably) be the only time I need to do this. What if I want to add a Health field that could be an int, or a float, etc? I'm now creating Player<Vector3,int> or Enemy<Int2, float> instances all over the place.

It sounds like what you need is to use composition over inheritance. A common way to do this in modern games is to use the Entity Component System approach.

If you go with this approach, both a Player and an Enemy should both just be an Entity. Then you can add whatever components they need, such as a Vector3Position component or a Int2Position component. Also IntHealthComponent and FloatHealthComponent.

There is a Entity Component System library named Artemis which has been ported to C# (I haven't used this myself, but I believe it's suitable enough for your needs). You can also make a Entity Component System implementation yourself, which many others have done on Code Review already (see entity-component-system)

To get an additional understanding of ECS, there is also an excellent question on GameDev StackExchange

Even though ECS is mostly used in real-time games, it is also possible to use it in turn-based games, which I have started doing myself in my Trading Card Game code.


LeetCode 76: Minimum Window Substring - Java

I have some suggestions.
Extract some of the logic to methods.
In your code, I see at least three sections of code that could be in methods. In my opinion, those extraction will help with the reading and make the code a bit shorter.

The validation of the parameters.

Before
if (string == null || target == null || string.length() == 0 || target.length() == 0 || string.length() < target.length()) {
   return "";
}

After
public String minWindow(String string, String target) {
   //[...]
   if (haveInvalidParameters(string, target)) {
      return "";
   }
   //[...]
}

private boolean haveInvalidParameters(String string, String target) {
   return string == null || target == null || string.length() == 0 || target.length() == 0 || string.length() < target.length();
}

The map initialization.

Before
//[...]
Map<Character, Integer> map = new HashMap<>(targetLength);
for (char character : target.toCharArray()) {
   map.put(character, -~map.getOrDefault(character, 0));
}
//[...]

After
public String minWindow(String string, String target) {
   //[...]
   Map<Character, Integer> map = initializeMap(target, targetLength);
   //[...]
}

private Map<Character, Integer> initializeMap(String target, int targetLength) {
   Map<Character, Integer> map = new HashMap<>(targetLength);
   for (char character : target.toCharArray()) {
      map.put(character, -~map.getOrDefault(character, 0));
   }
   return map;
}

The substring section.

Before
public String minWindow(String string, String target) {
   //[...]
   return flag == true ? string.substring(minLeft, -~minRight) : "";
}

After
public String minWindow(String string, String target) {
   //[...]
   return applySubstring(string, minLeft, minRight, flag);
}

private String applySubstring(String string, int minLeft, int minRight, boolean flag) {
   return flag == true ? string.substring(minLeft, -~minRight) : "";
}

Try to keep the variable declarations at the top of the blocks.
Generally in Java, we try to put the variable declarations at the top of the blocks.

Code Conventions for the Java (Revised April 20, 1999)

Before
int left = 0, right = 0;

After
int minLeft = 0, minRight = 0, min = string.length();
int left = 0, right = 0;

You can simplify the boolean expression
return flag == true ? string.substring(minLeft, -~minRight) : "";

is equals to
return flag ? string.substring(minLeft, -~minRight) : "";


I sometimes hear people say how they can distinguish between good and bad coders of a certain programming language or even programming in general simply by looking at the code they write.

I think that's true, to some extent. How else (except by the code they write) would you judge a programmer's ability?

Distinguishing programmers from their code is just the beginning though: see this answer for example.

Professional-level programming might also be categorized e.g. with Programmer Competency Matrix

  I was just wondering whether my program follows best practices

Not all the best practices; it could still be improved, for example:

Avoid macros (#define)
Format it well (use indentation)
Give good user output (better than "Enter something:  ")
Use subroutines (don't put everything in main)
Don't overflow your input buffer (e.g. if the end-user enters more than 10 words, or words more than 20 characters long)
Use library methods appropriately (e.g. not printf("%c" when you want to output a whole string and not just one character)
Use good identifier names (e.g. I'd prefer row and col, or x and y, or imax and jmax, instead of count_1 and count_2)
Be flexible in handling input correctly (e.g. I'd prefer arbitrary-length words and arbitrary-many words, which would require you to use a heap-based list or array of variable/infinite-length strings, instead of a fixed-size array)

  I know the next bit is a bit opinionated, but does my code give an idea of where I'm at with logic and programming as a whole

I think so. The code matches where you said you're at, which is that you are "relearning C".

Working a 40-hour week makes about 2000 hours per year.

So an adult professional programmer will have spent many 1000s of hours of practice and studying.


Object Attribute Stored in New List from Existing List of Objects

In terms of performance, to create a list of ages, [i.get_age() for i in person_list] is about as good as you'll get. The only real way to avoid this is to adjust the mean, median, and mode functions to accept a key parameter (much like the built-in sort function does) so that each function will access the correct attribute of the object. I wouldn't worry about removing that list comprehension though. Unless person_list is huge, and you require this code to run often, and as fast as possible, that would be a premature optimization.
Another way to potentially speed it up would be to have a single function that iterates the list once, and calculates all three statistics in one go. Again though, I would consider that to be premature unless you had a very good reason to optimize that.
Your solution is fine until you run into a situation in which it isn't performing well. Favor readability and simplicity until performance becomes an actual concern (or you have good reason to believe that it will become an actual concern in the near future).


Inter Thread Communication Even Odd Example

There is some refactoring that could be made.

Naming

EvenThread and OddThread aren't really threads since they don't implement the Thread class. There are two options:

Rename the two classes to something more appropriate/fitting with its purpose

e.g., EvenRunner/OddRunner

Move the thread management to the InterThreadCommunicationEvenOddExample.main method. This is more standard.

Redundancy

OddThread and EvenThread have almost the same functionality; a NumberThread could be created that paramaterizes the parity (e.g., a Parity enum parameter). This would be ideal since the logic in run() would only need to be changed once if needed.
The above point could be applied to getNextOdd and getNextEven in a similar manner.

Modifiers

Some variables could use tighter modifiers to better convey their purpose.

NumberResource numberResource could be final in all of its occurrences.
private boolean isEven(int number) could be made static since it is constant with respect to each NumberResource instance; furthermore, a semantic argument could be made that isEven(number) is not asking whether the NumberResource instance is even but rather asking if the provided number is even.

Threads

There is no need to call Thread.sleep() inside EvenThread.run() or OddThread.run(), since there is a wait() and notify() statement in the NumberResource's block. A single thread at a time will "wake up" from the wait() call after notify() is called in another thread, so removing the Thread.sleep() calls won't burn CPU cycles.
If the Thread.sleep() call is there for the sole purpose of text not flashing quickly onto the screen, then that is fine. Though moving the Thread.sleep() into the NumberResource method(s), before the notify() call, would cause text to be printed more evenly.

Empty catch statements

Either log something here or write a comment explaining why no action is taken here.
Allowing getNextOdd/getNextEven to throw an InterruptedException exception might even be cleaner.
A javadoc string for each method/class could clarify this as well.

Spacing

Overall, the spacing is fine and consistent, but 3 empty lines between each class method seems like too much, but this is subjective.

It is interesting to note that the overall output order of the messages is not guaranteed since notify() is called inside of getNextOdd/getNextEven; however, it is guaranteed that each Even Thread::{num} message will be strictly increasing (by 2). The same goes for each Odd Thread::{num} message.
Below is an example of some of the refactoring comments made above (except adding Javadocs).

public class InterThreadCommunicationEvenOddExample {
    public static void main(String[] args) throws InterruptedException {
        final NumberResource numberResource = new NumberResource();
        final Thread[] numberThreads = new Thread[] {
            new Thread(new NumberRunner(numberResource, Parity.EVEN)),
            new Thread(new NumberRunner(numberResource, Parity.ODD)),
        };

        for (Thread numberThread : numberThreads) {
            numberThread.start();
        }

        for (Thread numberThread : numberThreads) {
            numberThread.join();
        }
    }
}

class NumberResource {
    private int number = 0;

    public synchronized int getNextNumber(Parity parity) throws InterruptedException {
        while (getParity(number) != parity) {
            wait();
        }
        final int nextNumber = number++;
        notify();
        return nextNumber;
    }

    private static Parity getParity(final int number) {
        return number % 2 == 0 ? Parity.EVEN : Parity.ODD;
    }
}

class NumberRunner implements Runnable {
    private final NumberResource numberResource;
    private final Parity parity;

    NumberRunner(final NumberResource numberResource, final Parity parity) {
        this.numberResource = numberResource;
        this.parity = parity;
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.printf("%s Thread::%d\n", parity.name(), numberResource.getNextNumber(parity));
            } catch (InterruptedException e) {
                System.out.println("Interrupted while trying to retrieve next number.");
                return;
            }
        }
    }
}

enum Parity {
    EVEN,
    ODD,
}


you don't free s which means you have a memory leak
*(begin+1) can be rewritten as begin[1], which is much clearer
1 char variable names are very hard to get into, use longer/descriptive names where needed

the entire function can be rewritten as

void pascal(int limit)
{

    int *row;
    row=(int*)malloc(2*sizeof(int));
    row[0]=1;
    row[1]=1;

    for(int n=3;n<=limit+1;n++){

    printRow(buffer,n);

    int* nextRow = (int*)malloc((1+n)*sizeof(int));
    nextRow[0]=row[0];
    nextRow[n]=row[n-1];

    for(int i=1;i<n;i++){
        nextRow[i]=row[i-1]+row[i];
    }
    free(row);
    row=nextRow;

    }
}

instead of the malloc->assign->free sequence I could have used realloc and then worked backwards:

row = (int*)realloc(row,(1+n)*sizeof(int));
row[n]=0;

for(int i=n;i>0;i--){
    row[i]+=row[i-1];
}

but this is less clear


if ( (day > 0 || day < 7) && (t > 18 || t < 8))

Is this what you want?

Second condition will only be evaluated only if the first one is true. If the first one is true, then only the second one is evaluated.


Use Players.SingleOrDefault() instead of Where and FirstOrDefault.
If you use the function GetPlayer just one time, remove it.

public ServerPlayer GetServerPlayer(string playername)
{
    ServerPlayer player =  Players.SingleOrDefault(x => x.UserName == player name);
    if (player == null)
    {
        player = new ServerPlayer() {
            Server = this,
            UserName = playername,
        };

        Players.Add(player);
    }

    return player;
}

Personally, I think you should change GetServerPlayer to GetOrCreateServerPlayer especially if you are a team. We don't have to know or look your function to understand its purpose. Or keep the name and add the appropriates comments (summary, return, etc).

In the case of ASP.NET which follow MVC pattern, I think you must separate the logic and the model.
For my part I create Manager for logic and my controller just serve to call the appropriates methods of my manager.


Headers

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

Some issues here. You definitely don't need all those headers. Proon out the ones you don't need. The problem with putting them all in is that this can hide missing dependencies (if this was a header file and included by other header files).

Normally I don't care much about the order of headers (usually there is some logic there and everybody has their own). But sorting by filename length of include seems a bit odd. I have seen people sort by alphabetical order (not my favorite but it has options and I see the merit). Personally I put things into logical (to me) groups; I put container stuff together, stream stuff together, algorithm stuff together and meta programming stuff together. I put all my C++ headers before my C header.

Maps

If you access an element in a map and it does not exist then it is automatically created and "zero-initialized". This means you don't need to search and conditialy update.

  unordered_map<int, int> frequencyMap;
  for (int i = 0; i < n; i++) {
    auto mapIt = frequencyMap.find(arr[i]);
    if (mapIt == frequencyMap.end()) {
      frequencyMap.insert(make_pair(arr[i], 1));
    } else {
      frequencyMap[arr[i]]++;
    }
  }

Can be simplified too:

  unordered_map<int, int> frequencyMap;
  for (int i = 0; i < n; i++) {
      ++frequencyMap[arr[i]];
  }

VLA

Variable length arrays are an extension of C (part of C99). They were never part of the C++ standard. So this is not legal C++.

cin >> n;
int arr[n];

Your compiler supports it as an extension to the language but its not a good idea to use it. We use std::vector as a better alternative:

cin >> n;
std::vector<int> arr(n);

This also allows you to use range based for loops:

  unordered_map<int, int> frequencyMap;
  for (int val: arr) {
      ++frequencyMap[val];
  }

Order by frequency.

I like your idea of ordering by frequency using a std::map but it becomes clunky when you also have to order by value (and thus have a map of std::set). I would simply copy the frequency info into a vector and use a sort.

using Val = std::pair<int, int>;
std::vector<Val>  values(std::begin(frequencyMap), std::end(frequencyMap));
std::sort(std::begin(values), std::end(values), [](Val const& lhs, Val const& rhs)
  {
    return (lhs.second < rhs.second) || (lhs.second == rhs.second && lhs.first < rhs.first);
  });

Standard Issues from Beginners

Don't use

using namespace std;

This is a crutch that will break for you. Don't get into the habit of using it when it breaks it is not obvious and can lead to hours of debugging. The reason the standard namespace is called std and not standard is so prefixing object in the standard namespace is not that burdensome.

std::vector<int>  val;  // not that hard to add std::

Don't return an array from a function

 return solution;

You are returning the address of a local variable. Once this goes out of scope that variable no longer exists. So you have an invalid pointer returned. This is also another good reason to use std::vector as the copy/move semantics will correctly move it from the current scope to the calling scope.

PS. Your compiler should warn you about this.

No need to use return in main

return 0;

The compiler plants a return 0 at the end of main.

By not planting a return in main() it is an indication that your application does not have a failing state (usual for simple code). If it does have a user inserted return 0 I always start looking for other places it could return an error code. By not putting a return 0 you indicate to me that there is no error situation and I don't have to look for it.

Prefer pre increment to post increment

for (int i = 0; i < p.first; i++)

for (int i = 0; i < p.first; ++i)

In this case there is basically no difference. But there are situations where the post increment is slightly more complex.

What happen if we change i from an int into an iterator. Then it is a class the executes a function. Most iteratros behave like POD types with pre/post increment but to do that the post increment is slightly more complex. So why not use the one that will always give you optimal code (even if you change the type). So prefer pre-increment.

Prefer '\n' over std::endl

The difference is that std::endl will force a flush. In simple things like this it makes no difference. But if you are outputting a large amount of information then the extra flush can cause significant performance degradation.

The streams will auto flush themselves and having a human forcing a flush is always non optimal. So prefer to get the same resutls but at optimal speed with '\n'.

Pointer short hand

You should note that we have a shortcut pointer notation.

(*mapIt).second

// Shorthand as:
mapIt->second

Avoid short variable names

for (int i = 0; i < n; i++) {

This is great if your for loop is two lines long. But if the loop grows and becomes more complex then searching for all instances of i becomes a pain because of all the false positives.

Believe me just because your loop only covers two lines today, in ten years after thousands of bug fixes it will not look as neat. So give me something that is easy to search for in the code base.

I know a lot of people like using i as a loop variable. But this is a hold over from Foortran. Please use longer identifiers it will not cost you that much and the maintainer will not hunt you down with an axe.

Looks Like this:

#include <unordered_map>
#include <vector>
#include <iostream>
#include <iterator>

std::vector<int> customSort(std::vector<int> const& arr)
{
    std::unordered_map<int, int> frequencyMap;
    for (int val: arr) {
        ++frequencyMap[val];
    }

    using Val = std::pair<int, int>;
    std::vector<Val>  values(std::begin(frequencyMap), std::end(frequencyMap));
    std::sort(std::begin(values), std::end(values), [](Val const& lhs, Val const& rhs) {
            return (lhs.second < rhs.second) || (lhs.second == rhs.second && lhs.first < rhs.first);
          });

    std::vector<int> result;
    result.reserve(arr.size());
    for(auto const& val: values) {
        for(int loop = 0;loop < val.second; ++loop) {
            result.push_back(val.first);
        }
    }
    return result;
}

int main()
{
    std::vector<int> arr;

    int n;
    std::cin >> n;
    std::copy_n(std::istream_iterator<int>(std::cin), n,
            std::back_inserter(arr));

    std::vector<int> sorted = customSort(arr);
    std::copy(std::begin(sorted), std::end(sorted),
              std::ostream_iterator<int>(std::cout, "\n"));
}


Improving names:

Your class has 2 size variables, which looks kinda strange. Better to rename this private static one to something like INITIAL_CAPACITY (or DEFAULT_INITIAL_CAPACITY, if you have plans adding constructor with initialCapacity parameter), because size = how many elements are stored, but this variable denotes initial array length.
method hash in reality returns bucket index for given element, thus, should be renamed. For example, to indexFor or bucketIndex.

Other:

in Entry - next is not parameterized (as well as its getter and setter).


I looked at it twice and I do not see any kind of Bridge Pattern. I see a simple abstraction and some concrete implementations of it. "ApiClientExample" is maybe a wrapper. Technically it seems to me ok.

Nevertheless I'd like to comment on one semantic thing:

As the method "visit" is totally fine, the method "getDocument()" seems strange to me. Without totally rejecting it I'd make some research on the liskov substitution principle. You also should consider a wrong abstraction level or a wrong semantical assigment to the interface "CrawlerAPI" as the method "getDocument" is totally generic. Will the return value of "visit" be put into "getDocument()"? If so, the method is at the wrong place. You introduced a mental mapping and it would be more a cascading call than a method delared in the same interface.


There's no point in writing a separate class just to contain the main() function.  I'd rather invoke java GuessingGame than java Main.

while (GuessingGame.play) is bad in several ways:

GuessingGame exposes a public variable.  It's standard practice to require Main to call a method, so that no other class can write to a variable in the GuessingGame class.
The method GuessingGame.play() and the variable GuessingGame.play are too similarly named, which is confusing.
GuessingGame.play() sets the GuessingGame.play flag as a side-effect, which is unconventional and unintuitive.  It also violates the Single Responsibility Principle: play() should do one thing only.
A do-while loop might be more appropriate, since you want to play at least one game.

In GuessingGame, everything is static.  The number and guess variables could easily be made into local variables in play(), and therefore they should be.

Since the Random object is a class variable, there is no point in passing it as a parameter to nextInt().  There is a bug in nextInt(), in that it will never generate a 10.

Suggested solution

import java.util.Random;
import java.util.Scanner;

public class GuessingGame {

    private static Random random = new Random();
    private static Scanner scanner = new Scanner(System.in);

    /**
     * Picks a number uniformly between lowerBound (inclusive)
     * and upperBound (exclusive).
     */
    private static int nextInt(int lowerBound, int upperBound) {
        return lowerBound + random.nextInt(upperBound - lowerBound);
    }

    /**
     * Plays one game.
     *
     * @return true if the guess was correct
     */
    public static boolean play() {
        int number = nextInt(1, 10 + 1);
        System.out.println("Insert your guess from 1-10!");
        if (scanner.nextInt() == number) {
            System.out.println("Correct!");
            return true;
        } else {
            System.out.println("Wrong! The number is: " + number);
            return false;
        }
    }

    /**
     * Asks if the user wants to play again.
     */
    public static boolean shouldPlayAgain() {
        System.out.print("Do you want to try again? Y/N ");
        return "Y".equalsIgnoreCase(scanner.next());
    }

    /**
     * Plays guessing games until the user guesses correctly or gives up.
     */
    public static void main(String[] args) {
        while (!play() && shouldPlayAgain());
    }
}


I see that you're using Java 7, you could use the try-with-resource for all you're IO operation. It will close the stream you're using in your application.

 try{
            File newFile = new File("C:\\Media\\" + directory + "\\" + filename);

            inStream = new FileInputStream(originalFile);
            outStream = new FileOutputStream(newFile);

            byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes
            while ((length = inStream.read(buffer)) > 0){

                outStream.write(buffer, 0, length);

            }

            inStream.close();
            outStream.close();

            System.out.println("Original PDF has been copied successfully!");

        }catch(IOException e){
            e.printStackTrace();
        }

You're not closing your streams if there is an IOException. This could lead to some potential problem in a future application. To get ride of the problem you could use the try-with-resource syntax. Your code could look like :

File newFile = new File("C:\\Media\\");
try ( InputStream inStream = new FileInputStream(newFile);
      OutputStream outStream = new FileOutputStream(newFile);) {

    byte[] buffer = new byte[1024];

    int length;
    // copy the file content in bytes
    while ((length = inStream.read(buffer)) > 0) {

        outStream.write(buffer, 0, length);

    }

    System.out.println("Original PDF has been copied successfully!");

} catch (IOException e) {
    e.printStackTrace();
}

Argument name should not start with an uppercase letter : public static void convertPDFtoPNG(String PDFFileName). Do you need to capitalize pdf ?

I would revise some of you comments. Comments should be helpful, you don't need to repeat the code. Example :

 // load PDF document
 PDFDocument document = new PDFDocument();
 File baseFile = new File(PDFFileName);
 document.load(baseFile);

Does //load PDF document is really needed ? You're already using document.load. One liner comment are most of time just repeating what you are doing in code. Other readers don't need to know what you are doing, but rather why are you doing it. I am always wondering myself when I am adding a comment : Does my code is clear enough by itself ? Do I really to add a comment or could I change the method name or variable to better express myself. Comments are hard to maintain when the code is changing.

I know you're not in a production environment yet, but don't forget to change all the e.printStackTrace for a logging of some sort.

It is worth to know that you can use / for all of you path, instead of escaping \. Java will manage the one you need for the OS you're using.

You're saying that your converting a PDF to an image, but it's not quite true. In fact, you are converting a PDF to a jpeg, which is quite different IMHO. You are hard coding the creation of the image as an jpeg, you will probably want to change in the future to support more formats. You will probably extract the writing code of the image into his own method or interface so that you have multiple implementation for each format (if needed, I am not good in image at all).


Given a list of coordinates check if 4 points make a line

General remarks

def points_in_lins(l):

The function and argument name can be improved. l is too short and does
not indicate at all that this is a list of points, and points_in_lins
(perhaps you meant points_in_line?) does not indicate that the function
looks for four points in a line.

gradients is in fact a dictionary counting slopes.

Iterating over all pairs of points can be simplified with
enumerate() and slices:

for idx, (x1, y1) in enumerate(l):
    gradients = {}
    for (x2, y2) in l[idx + 1:]:

The “set or increment” for gradients can be simplified with
defaultdict or a Counter:

gradients = Counter()

# ...

gradients[m] += 1
if gradients[m] == 3:
    return True

The parentheses in return(True) and return(False) are not necessary:

return False

The math

Computing the slope as the quotient

m = (y2 - y1) / (x2 - x1)

requires a separate check for a zero denominator, but is problematic
for another reason: Rounding errors can occur. As an example,

points_in_lins([(0, 300000000000000000), (1, 0), (1, 1), (1, 2)])

evaluates to True: The slopes from the first point to the
other three points all evaluate to the same floating point number.

A possible fix is to compare the “directions” , i.e. the (2-dimensional)
vectors between the two points, normalized in a way such that
two vectors pointing in the same (or opposite direction) are
considered equal.

If all coordinates are integers, then it is best to stick with pure
integer calculations. Normalizing the connecting vector can be
achieved by division by the greatest common divisor of the x- and
y-component, and possibly mirroring it.

Putting it together

from math import gcd
from collections import Counter

def four_points_in_line(points):
    for idx, (x1, y1) in enumerate(points):
        direction_counts = Counter()
        for (x2, y2) in points[idx + 1:]:
            # Compute normalized direction from (x1, y1) to (x2, y2):
            delta_x, delta_y = x2 - x1, y2 - y1
            g = gcd(delta_x, delta_y)
            delta_x, delta_y = delta_x // g, delta_y // g
            if delta_x < 0 or (delta_x == 0 and delta_y < 0):
                 delta_x, delta_y = -delta_x, -delta_y
            # Three identical directions from (x1, y1) means 4 collinear points:
            direction_counts[(delta_x, delta_y)] += 1
            if direction_counts[(delta_x, delta_y)] == 3:
                return True
    return False

It is still a \$ O(n^2) \$ algorithm, but more robust against
rounding and division by zero errors.

If the points are not guaranteed to be distinct then  identical points need have to be treated separately.


The biggest problem with your PDO code is error reporting. die($e->getMessage()); is the worst method possible. Citing from my article on error reporting (which I highly recommend to read):

for the casual user the error message is pretty cryptic and confusing
it it essentially useless for the site programmer/admin as they likely won't be browsing the site at the moment and will have no idea that error has been occurred
the information provided in the error message is extremely useful for a potential hacker, as it provides them with the feedback for their actions and may leak some sensitive information about your site

So never write a try..catch operator unless you have a certain scenario to be executed in the catch block as it will be useless and harmful.

Another suggestion is just a matter of taste. Given you have only one variable in the query, you can use a positional placeholder instead of a named one, sparing yourself writing some extra code:

if(Input::exists()){
  $sql = "UPDATE `content` SET `edit_about` = ? WHERE `id` = 1";
  $query = $handler->prepare($sql);
  $query->execute([$_POST['message']]);
  Redirect::to(BASE_URL.'index');
}

As you may notice, the PDO code looks a bit different from the other code you are using. With a simple PDO wrapper could make this code even simpler and uniform:

if(Input::exists()) {
    $sql = "UPDATE `content` SET `edit_about` = ? WHERE `id` = 1";
    DB::run($sql, [$_POST['message']]);
    Redirect::to(BASE_URL.'index');
}

The example is taken from my PDO wrapper usage examples but you can use any wrapper you like.

Also, I don't know which framework you are using, but $_POST['message'] seems a bit alien to me. I would expect something like Input::get('message') instead.


ConvertAll Methods Implementation for Multidimensional Array in C# - follow-up

When I see that many recurrences like this then it is a good sign for me that this is a perfect place to introduce meta-programming via T4.
Step #1
Separate the overloads from the core logic:
using System;

namespace Sample.Core
{
    internal static class Converter
    {
        public static Array ConvertArray<T, TResult>(Array array, Converter<T, TResult> converter)
            where T : unmanaged
            where TResult : unmanaged
        {
            if (array is null)
            {
                throw new ArgumentNullException(nameof(array));
            }

            if (converter is null)
            {
                throw new ArgumentNullException(nameof(converter));
            }

            long[] dimensions = new long[array.Rank];
            for (int i = 0; i < array.Rank; i++)
                dimensions[i] = array.GetLongLength(i);

            Array result = Array.CreateInstance(typeof(TResult), dimensions);
            TResult[] tmp = new TResult[1];
            int offset = 0;
            int itemSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(TResult));
            foreach (T item in array)
            {
                tmp[0] = converter(item);
                Buffer.BlockCopy(tmp, 0, result, offset * itemSize, itemSize);
                offset++;
            }
            return result;
        }
    }
}

Step #2
Introduce a *.tt file with the following content:
<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
using System;
using static Sample.Core.Converter;

namespace Sample.Overloads
{
    public static class ArrayConverter
    {
<#
for(int i = 1; i < 10; i++)
{
var dimensions = new String(',', i);
#>
        public static TOutput[<#=dimensions#>] ConvertAll<TInput, TOutput>(TInput[<#=dimensions#>] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[<#=dimensions#>])ConvertArray(array, converter);
        }
<#
}
#>
    }
}

Step #3
Execute the tt file and examine the generated code:
using System;
using static Sample.Core.Converter;

namespace Sample.Overloads
{
    public static class ArrayConverter
    {
        public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[,])ConvertArray(array, converter);
        }
        public static TOutput[,,] ConvertAll<TInput, TOutput>(TInput[,,] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[,,])ConvertArray(array, converter);
        }
        public static TOutput[,,,] ConvertAll<TInput, TOutput>(TInput[,,,] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[,,,])ConvertArray(array, converter);
        }
        public static TOutput[,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[,,,,])ConvertArray(array, converter);
        }
        public static TOutput[,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[,,,,,])ConvertArray(array, converter);
        }
        public static TOutput[,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[,,,,,,])ConvertArray(array, converter);
        }
        public static TOutput[,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[,,,,,,,])ConvertArray(array, converter);
        }
        public static TOutput[,,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,,] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[,,,,,,,,])ConvertArray(array, converter);
        }
        public static TOutput[,,,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,,,] array, Converter<TInput, TOutput> converter)
            where TInput : unmanaged
            where TOutput : unmanaged
        {
            return (TOutput[,,,,,,,,,])ConvertArray(array, converter);
        }
    }
}
```


You are using classes as function containers. Path doesn't inherit from any of the other classes, yet you are passing your self instance to their initializer functions.

class _basePath:
    def __init__(self, **config):
        #Initialize Here
class Path:
    def __init__(self, flags, **config):
        _basePath.__init__(self, **config)

is no different from

def _base_path_init(instance, flag **config):
        #Initialize Here
class Path:
    def __init__(self, flags, **config):
        _base_path_init(self, **config)

You do the same thing in move() to access the specific move implementations.

If you take a step back, this code looks like it is trying to combine the concept of an object model with the concept of mixins or traits. Instead, if we take a step back and focus on the object model concept, the code can be simplified.

class Path(SGObject):
  def __init__(self, flags, **configs):
    SGObject.__init__(self)
    self._traits = []
    if flags & PATH_CLAMPED:
        self._traits.append(ClampedPath(self, **config))
    if flags & PATH_REVERSED:
        self._traits.append(ReversiblePath(self, **config))
    if flags & PATH_ACCELERATABLE:
        self._traits.append(AcceleratablePath(self, **config))

  def move(self):
    for trait in self._traits:
      trait.move(self)

Then each model would have the following interface.

class PathTrait(object):
  def __init__(self, instance, **configs):
     #Initialize Instance Here
  def move(instance):
     #Alter Instance Here

Notes:

The above assumes that the order of move operations needs to be enforced by Path (ie. ClampedPath's move must occur before ReversiblePath's move). If this is not the case, the initializer can be simplified to just take a list of model classes.

class Path(SGObject):
  def __init__(self, traits, **configs):
    SGObject.__init__(self)
    self._traits = [t(self, **config) for t in traits]

This allows you more flexibility in the future and removes the needs for flags entirely.

The way to code is written now, _clampedPath introduces the concept of movement no longer being allowed. If the path is clamped and it has finished, should the other traits execute at all?


Reverse dictionary where values are lists

There's really not much to say about this code, it is straightforward.

Style

These are only nitpicks.

Generic dictionary keys are typically named k instead of i or j, but in a specific application a more descriptive name would be even better.
Collections should be named by their purpose in the application, not their type.
By convention, assignments and other binary operators should be surrounded by spaces: a = b, not a=b. See PEP 8 for reference, if you're not already aware of it. Following this style guide makes your code easier to read for others.

Code improvements

When iterating over the keys and values of a dictionary at the same time, you can use

for k, v in dic.items():
    # ... use k, v ...

instead of

for k in dic:
    v = dic[k]
    # ...

The nested loop can be transformed to a dictionary comprehension like this:

dic2 = {v: k for k, values in dic.items() for v in values}

You can remember that the order of for clauses in the comprehension is the same as the order of corresponding nested for loops.

Potential pitfalls

You should be aware that this transformation from a dictionary of lists to a reverse dictionary only works if all items in the original lists are unique. Counterexample:

>>> dic = {0: [1, 2], 1: [2, 3]}
>>> {v: k for k, values in dic.items() for v in values}
{1: 0, 2: 1, 3: 1}  # missing 2: 0

To correct this, the output dictionary should have the same format as the input, namely mapping each of the items in the input lists to a list of corresponding keys.

If the input represents a directed graph (mapping nodes to lists of neighbours), this corresponds to computing the transposed or reversed graph. It can be done by using a collections.defaultdict. I don't see an easy way to write it as a comprehension in this case.

from collections import defaultdict

graph = {0: [1, 2], 1: [2, 3]}

transposed_graph = defaultdict(list)
for node, neighbours in graph.items():
    for neighbour in neighbours:
        transposed_graph[neighbour].append(node)

# {1: [0], 2: [0, 1], 3: [1]}


Code Review
This initializes all members to zero:
    int map_cherries[70][70][70] = {};

Then you manually initialize the map again:
        std::memset(map_cherries, -1, sizeof(map_cherries));

This is not doing what you think it is doing.
        std::memset(map_cherries, -1, sizeof(map_cherries));

This is initializing every byte to -1. Each integer is probably 4 bytes (or more long). So each byte is being set to -1. Now it happens that in 2's compliment this work (if you set all bytes to -1 then the integer is also -1). But there is no guarantee in the standard that C++ will use 2's compliment as the representation of integers (even if it is very common).

This returns a const inline int!
    const inline int depth_first_search(
        ...
    )

I know it is legal but come on. That's hard to read. If you have to add inline put it first so we can make the return type readable.
    inline const int depth_first_search(...)

Now we can see that the return type is const int. That still does not make that much sense. Just return the an int.
The inline keyword has no functional use to the C++ compiler (the compiler writers stopped believing developers had a good idea about this years ago). So this keyword has no effect on the code being generated. The only reason it is used is when the function is defined in the header file but not in the class it is needed to let the linker know there may be multiple definitions (as it may have been included multiple times). But when the method is part of the class this is redundant as it is automatically inline.
The general consensus is don't use inline unless you need to use inline. The only time you need to use inline is for method definitions in header files where they are not defined as part of the class.
    int depth_first_search(...)

If you don't intend to modify a reference pass it by const reference.
    const inline int depth_first_search(
        std::vector<std::vector<int>> &grid,
         ...
    )

This will prevent mistakes where you accidentally modify the data.

Nice short circuit here.
        if (row == row_length) {
            return 0;
        }

But here: Not sure this will ever happen!
Nice optimization. I like it.
        if (map_cherries[row][left_robot][right_robot] != -1) {
            return map_cherries[row][left_robot][right_robot];
        }

It took me a while to spot this as an optimization. I would add a comment on WHY this is working and how this is a shortcut optimization.

This if statement is a bit complex. I would split it into a couple of statements.
                if (curr_left_robot > -1 and curr_left_robot < col_length and curr_right_robot > -1 and curr_right_robot < col_length) {

                 // You can do in 1 statement if you want.
                 // But I like the use of a function here as it tells you
                 // what the test is and thus documents the code is doing.
                 if (!inBounds(curr_left_robot)) {
                     continue;
                 }
                 if (!inBounds(curr_right_robot)) {
                     continue;
                 }

Sure that's legal.
        return map_cherries[row][left_robot][right_robot] = max_cherries + cherries;

Makes the line very long though.
I would split into three lines;
        // Add cherries in this row to the previous row.
        cherries += max_cherries;

        map_cherries[row][left_robot][right_robot] = cherries;
        return cherries;


The title of the question is confusing. The code seem to check if the text is not the same if you read it backward. For example, it $b will be true for "hello" and false for "level". In other words, you're checking if some text is NOT a palindrome. I think you should change the title to better reflect what the code is doing.

Things to improve:

It's enough to iterate until strlen($text) / 2, no need to go all the way until the end
To avoid re-calculating the length of the string, it's better to calculate it once before the loop and reuse it
Wrap the whole thing in a function to make it easier to reuse and to test
The !== is unnecessary, a simple != would do

For example:

function isPalindrome($text) {
    $length = strlen($text);
    for ($i = 0; $i < $length / 2; $i++) {
        if ($text[$i] != $text[$length - 1 - $i]) {
            return false;
        }
    }
    return true;
}

function test_isPalindrome($text) {
    printf("isPalindrome(%s) -> %s\n", $text, isPalindrome($text) ? 'YES' : 'NO');
}

test_isPalindrome("reverseesrever");
test_isPalindrome("hello");
test_isPalindrome("aba");
test_isPalindrome("aa");
test_isPalindrome("ab");

Outputs:

isPalindrome(reverseesrever) -> YES
isPalindrome(hello) -> NO
isPalindrome(aba) -> YES
isPalindrome(aa) -> YES
isPalindrome(ab) -> NO


This looks mostly fine by me (ignoring Reflection and other more obscure sources of thread safety failures), but I wouldn't call it a Queue per say (because of the duplicate check there). Does it really matter what order the set of items in this collection are in (if so then the duplicate check introduces a bug in that ordering, if not then why not call this a Set)?
One change you should really make is adding readonly to your private members.
Also, while this looks thread safe, there is no reason to assume that it is safe to use any of the items inside of it or any inherited versions of it. Consider code like this (intended to obviously be unsafe):
public class NotThreaSafeExampleClass {
    public Action<string> SayHello;
}

//thread 1: (q = shared ThreadedQueue<NotThreaSafeExampleClass>)
var mean = new NotThreaSafeExampleClass();
q.Enqueue(mean);
while (true) {
    mean.SayHello = name => { Console.WriteLine("Hi "+name); };
    Thread.Sleep(10);
    mean.SayHello = null;
    Thread.Sleep(10);
}

//thread 2:
NotThreaSafeExampleClass otherThreadMethod;
q.TryDequeue(out otherThreadMethod);
while (true) { otherThreadMethod.SayHello('odyodyodys'); Thread.Sleep(15);}

Lock based concurrency in .NET is a fairly simple paradigm (compared to the other ways of ensuring thread safety in .NET). When you lock, you declare a block of code as a critical section, protected by that lock object. .NET ensures that a second piece of code in the same app domain will never be running in a critical section protected by the same lock object while one instance is. Here is a good resource for more threading information: http://www.albahari.com/threading/part2.aspx
Pedantry
When most people discuss thread safety they mean it in the same sense as saying strings are immutable. That is to say, as long as you don't do anything I shouldn't reasonably expect you might do it is safe.
Unfortunately, locks aren't good enough to actually provide true thread safety (bulletproof against reflection and unsafe C# pointer code), they are good enough for most usages where you control the software stack out to the actual application. If you need to ensure thread safety in these instances you must ensure thread safety at the field level in your classes (stuff like the volatile keyword will help you here, but watch out).
Some example threads that would break your safety here:
//as an additional thread running in the app, this would effectively make the locks no longer exclusive
var l = q.GetType().GetField("_queueLock", BindingFlags.NonPublic|BindingFlags.Instance);
while (true) { l.SetValue(q,new object()); }
//making the lock object readonly would protect against this

//ex 2:
var qf = q.GetType().GetField("_queue", BindingFlags.NonPublic|BindingFlags.Instance);
var field = (Queue<TType>)qf.GetValue(q);
field.Clear(); //what if this will happen between the Count check and the Dequeue statement
//readonly will not protect against this

While these examples are pretty far out there, consider if your Queue class were complex enough that I might want to add an extension method to it and need access to internal variables in the method to do some algorithm in a way much better than possible with the available public interface.


Window-size-dependent navigation menu with animation effects

Easier to Read

Make sure you use the same standard everywhere, indent nicely and be consistent. Then the code already looks a lot better:

/*
HEADER NAVIGATION
*/

/* navigation tabs click highlight */
$(".header-main-tabs").click(function() {
    $(".header-main-tabs").removeClass("header-tab-selected");
    $(this).addClass("header-tab-selected");
});

/* drop menu hide and show for desktop */
$(".header-main-tabs").hover(function() {
    $(this).children(".header-drop-menu").toggleClass("show-drop-menu-hover");
});

/* search input hide and show when search icon is pressed */
$("#search-icon-container span").click(function() {
    $(this).toggleClass("fa-times");
    $("#search-input-container").fadeToggle("fast");
});

/* mobile navigation */
/* show mobile tabs when toggle nav mobile button is clicked and when browser width is      over 990px */
/* toggle mobile navigation when nav button is clicked */
$("#toggle-mobile-nav").click(function() {
    $("#nav-tabs-list").slideToggle();
    $("#toggle-mobile-nav").toggleClass("toggle-mobile-nav-clicked");
});

var browserWidth = $(window).width();

$(window).resize(function() {
    browserWidth = $(window).width();
    if (browserWidth > 990) {
        $("#nav-tabs-list").show();
    }
});

$('#nav-tabs-list li').click(function() {
    if (browserWidth <= 990) {
        $('#nav-tabs-list').slideUp();
    }
});

/* always show drop menu when on mobile version (when browser width is below 960px) */
$(document).ready(function() {
    fadeMobile();
});

$(window).resize(function() {
    fadeMobile();
});

function fadeMobile() {
    browserWidth = $(window).width();
    if (browserWidth < 990) {
        $("#nav-tabs-list").hide();
        $('.header-drop-menu').show();
        $("#toggle-mobile-nav").removeClass("toggle-mobile-nav-clicked");
    }
}

Shorter

Don't use $('...') twice for the same selector and don't use it in an event. Instead, save the element in a variable and use that. It's both faster and easier to read
Group events on the same element. The first 2 events are both placed on $('.header-main-tabs'), group them together
Put all code in the $(document).ready() callback, this will avoid "DOM not ready" errors
Use CSS to hide/show elements, don't use jQuery for that
Combine the same events, you now have 2 $(window).resize() events
Don't show on each resize, only show if it was hidden before
Don't use global variables to store data

/*
HEADER NAVIGATION
*/

$(document).ready(function () {

    var $mainTabs = $(".header-main-tabs");
    var $searchInputContainer = $("#search-input-container");

    $mainTabs
        .click(function() { // navigation tabs click highlight
            $mainTabs.removeClass("header-tab-selected");

            $(this).addClass("header-tab-selected");
        })
        .hover(function() { // drop menu hide and show for desktop
            $(this).children(".header-drop-menu").toggleClass("show-drop-menu-hover");
        });

    /* search input hide and show when search icon is pressed */
    $("#search-icon-container span").click(function() {
        $(this).toggleClass("fa-times");

        $searchInputContainer.fadeToggle("fast");
    });

    /* mobile navigation */
    /* show mobile tabs when toggle nav mobile button is clicked and when browser width is      over 990px */
    /* toggle mobile navigation when nav button is clicked */
    var $navTabsList = $("#nav-tabs-list");
    var $toggleMobileNav = $("#toggle-mobile-nav");
    var $headerDropMenu = $('.header-drop-menu');

    $toggleMobileNav.click(function() {
        $navTabsList.slideToggle();

        $toggleMobileNav.toggleClass("toggle-mobile-nav-clicked");
    });

    $(window).resize(function() {
        browserWidth = $(window).width();

        if (browserWidth > 990 && $navTabsList.is(':hidden')) {
            $navTabsList.show();
        }

        fadeMobile();
    });

    $('li', $navTabsList).click(function() {
        if ($(window).width() <= 990) {
            $navTabsList.slideUp();
        }
    });

    /* always show drop menu when on mobile version (when browser width is below 960px) */
    fadeMobile();

    function fadeMobile(browserWidth) {
        if (browserWidth < 990) {
            if ($navTabsList.is(':visible')) {
                $navTabsList.hide();
            }

            if ($headerDropMenu.is(':hidden')) {
                $headerDropMenu.show();
            }

            if ($toggleMobileNav.hasClass('toggle-mobile-nav-clicked')) {
                $toggleMobileNav.removeClass("toggle-mobile-nav-clicked");
            }
        }
    }

});


You need to be very careful when making code like this multithreaded.  Your implementation will compile, and will execute the GetMarketInfoAll() method on another thread, but it may not do what you want.  There are at least two things to consider:

Synchronization:
The lambda function given to ContinueWith can (and often will) be executed on a different thread from the one that called RequestMarketInfo.  The lambda function in your code invokes an event handler, this means that the code inside the event handler may need to synchronize any data it accesses, or you will end up with race conditions and other threading issues.
Thread Affinity:
Similar to the first point, it may be necessary for you to ensure that the event handler is invoked on a certain thread.  If any of the handlers for the OnMarketInfoUpdated event are updating a UI component in Windows Forms, then you will certainly need to perform those updates on the UI thread using Invoke.

You should also note that depending on the type of application you are developing, it may not actually help you to convert this to async.  For example, web applications under heavy load are already using 1 thread per web request, and are often maxed out.  However, I suspect you are using this inside a GUI and are trying to make the UI more responsive while it processes this long running query, in which case converting this to async is a good idea.


Instead of setting the active property to an element in the array, set it to the index of the element.

The reason for this being that almost all your operations are on the index and not the element itself. You only use that once: when you display the element. You can then eliminate your calls to indexOf because you already have the result. You can also simply the logic around first and last by centralizing it.

var app = angular.module('app', []);
app.controller('ctrl', ['$scope',
    function ($scope) {
        $scope.hello = 'hello world';
        $scope.boxes = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
        $scope.active = 0;
        $scope.move = function (x) {
            if(x) {
               //while incrementing keep the index in bounds using min
               $scope.active = Math.min($scope.active+1,$scope.boxes.length - 1);
            } else {
               //while decrementing keep the index in bounds using max
               $scope.active = Math.max($scope.active-1,0);
            }
        };
        $scope.$watch('active', function (active) {
            //it's usually possible for the first element to be the last as well
            //so unless you know you'll never have an array with 1 element
            //don't use an if-else here
            $scope.first = active == 0;
            $scope.last = active == $scope.boxes.length - 1;
        });
    }
]);


I'm pretty sure the js convention is still to prefix "private" stuff with an underscore.
class QuickSort {
  sort(a) {...}
  _sort(a, lo, hi) {...}
  ...}

The only other thing that sticks out to me is your use of ++ and -- in the while loops. While perfectly idiomatic, I think it would express the logic better to move both conditionals together in the while(condition), and the increment action into the while's body. Of course it's always nice if one can abstract away a loop altogether...
Other people can speak more specifically about javascript than I can.


Dynamically generated attribute accessors in Perl

If Moose is an overkill, you can try Moo instead. There are some even simpler distributions like Class::Tiny or Object::Tiny. They are probably better tested than your own solution as their user base is larger. They might also be faster (more optimized) and play well with inheritance and roles.