Generate a Jekyll blog post template using shell

Overall, it is clear and well formatted.  Here are some suggestions:

shellcheck.net

Firstly, I highly recommend running your scripts through shellcheck.net.  This reveals:

Where you're using $filepath you should use "$filepath" in case part of the path contains spaces.  Although shellcheck didn't catch it the assignment to filepath= should have quotes around the right side so it doesn't get broken up.
cd can fail and you should check the exit code, but in your case you're just using it inside of a subshell so it is probably fine as is.

double brackets

Using double brackets for conditionals in the shell is a good habit to get into.  They won't surprise you when people leave variables empty, for instance.  So

if [ -z "$title" ]; then

should be

if [[ -z "$title" ]]; then

bug

Where you check for the files existence you don't substitute the variable, you're checking for the existence of a file named filepath which probably never will be there.  Replace:

if [ -f filepath ]; then

with

if [[ -f "$filepath" ]]; then

to get the desired result.  I'm also using the quotes around the variable and double brackets previously mentioned.

heredocs

Instead of repeatedly appending to your file, why not do it in one fell swoop:

cat << EOF >> "$filepath"
---
layout:      post
title:       "$title"
date:        "$(date +"%Y-%m-%d %H:%M:%S %z")"
categories:  [weekly]
---
EOF

That can replace your block of echos.  Now you don't have to worry about escaping your double quotes and the template is clearly separated from the code.  Heredocs also make it easier to edit the template within the script without messing up what the code is doing.

finally

Thanks for posting your shell script on codereview and trying to get better.


Your indentation is off. if should be at the same level as the corresponding else or else if, their bodies being indented once. Don't wander all the way to the right.

You are missing the include for std::string, <string>.

using namespace std; seems convenient, right? Unfortunately, throwing everything and the kitchen sink into the global namespace and praying it works is error-prone.
See "Why is “using namespace std;” considered bad practice?".
I wouldn't even use a using-declaration here, though that would be unproblematic at least.

return 0; is implicit for main(). (And only for that function.)

You never test whether reading (and/or writing) succeeds. At least that's pretty harmless in your program. Still, consider ending with:
    return !!std::cin || !!std::cout;

Swapping is often far more efficient than copying. Consider using a.swap(b) or the more generic using std::swap; swap(a, b); two-step, the latter is in <utility>.

Only use std::endl when you need to flush the stream. Actually, belay that, be explicit and use std::flush.
Hint: std::cin and std::cout are tied, which you already take advantage of with your prompt. Also, when the program ends the standard streams are flushed.
See "What is the C++ iostream endl fiasco?".

Comparing strings is likely to be comparatively expensive. Thus, compare two strings, and then make different decisions depending on the outcome.

An alternative to considering each case separately is writing a sorting-network.
You would be well-advised to abstract a conditional swap into its own function if you go that way:
void sort2(std::string& a, std::string& b) noexcept {
    if (b < a)
        b.swap(a);
}


You can move setting properties to lazy var declarations eg.

lazy var centerStackView: UIStackView = {
  let stackView = UIStackView()
  stackView.translatesAutoresizingMaskIntoConstraints = false
  stackView.axis = .vertical
  stackView.distribution = .fillEqually
  return stackView
}()

This will divide your code nicely. In my opinion, extracting views to separate files has a sense only if they have a more complex structure and you want to reuse them in other places. What is important is keeping functions short and on point. Also, try to use more empty lines to visually divide logic blocks, eg. adding subview and setting constraints to it from another subview.


Resize image with good quality and less weight

Variable type choice. Why do you use Int16 and float? Most likely you'll be running on a 32-bit or 64-bit machine, and even the 32-bit machines will be optimized for math operations using double. I know you don't need perfect accuracy, but using the smaller types is not likely to save you any space or time. The optimizer will probably convert them to Int32 and double anyway and then just round them off/truncate/extend.
You should declare variables as late as possible. Ideally right before they're initialized. In particular, there's no point in declaring a variable, setting its initial value to 0, and then on the next line setting its value to what you really wanted.
What is the purpose of nPercent, destX, and destY? You calculate them then throw them away.
I don't think you tested this code. You have an if block that swaps newWidth and newHeight, but nothing that ever swaps them back. What's the code intended to do?


I would suggest swapping the checks on this line from

where moduleType.IsAssignableFrom(assemblyType) && !assemblyType.IsAbstract

to

where !assemblyType.IsAbstract && moduleType.IsAssignableFrom(assemblyType)

Checking a boolean property will be faster than a method call to check the type. If it's not abstract why check the type?

You might also want to filter further by requiring that it is a class:

where assemblyType.IsClass
      && !assemblyType.IsAbstract
      && moduleType.IsAssignableFrom(assemblyType)


Type strength
Unless you have a really (really) good reason to use a dict - such as planning to immediately serialize to JSON for some network operation - dict is a poor choice for an internal representation. Use a @dataclass.
Parsing strictness
You should be a little more strict about your parsing; your current implementation considers
check_name_for_something_that_makes_no_sense

to be a check_name heading, and a data entry under the run: heading called
check_name

to be a heading instead of a data entry. Instead, just compare the whole line.
Your example data do not show any reason for your - check to be there, so I see no reason for it to exist.
Parse state
Instead of hanging onto flags to remember parse state, you can simply assign a reference to the list currently being populated.
Explicit iteration
No need to call readlines. Just iterate over the file object itself.
Example implementation
from dataclasses import dataclass
from typing import TextIO, List

@dataclass
class RunData:
    name: str
    run: List[str]
    not_run: List[str]

    @classmethod
    def from_file(cls, f: TextIO) -> 'RunData':
        run = []
        not_run = []
        current_list = None
        name = None

        for line in f:
            line = line.rstrip()
            if line == 'run:':
                current_list = run
            elif line == 'not run:':
                current_list = not_run
            elif line.startswith('check_name :'):
                name = line.split(': ', 1)[1]
            elif line == 'End':
                return cls(name, run, not_run)
            else:
                current_list.append(line)

def main():
    chk_cell = "input.txt"
    with open(chk_cell, "r") as fchk_cell:
        chk_cell_data = RunData.from_file(fchk_cell)
    print(chk_cell_data)

if __name__ == "__main__":
    main()

prints
RunData(name='xa25', run=['inv_w_', 'buf_w_'], not_run=['del_l6w_', 'dl_l4w_', 'dl_l22w_', 'de_l3w_', 'ckt_pw_', 'ckt_pw_'])


Converting a range of integers from a string to an IEnumerable

Ok, some comments:

Code style

While there are no definitive laws about code style, most C# programmers are putting the opening brace { on a separate line. If someone else is going to read your code, they are likely to be annoyed.
Consider breaking up the method into smaller methods to clarify how it works, which is better than adding comments.

Nesting, minimizing nesting makes the code easier to read and in this case you can certainly remove a few levels, namely:

if (!string.IsNullOrWhiteSpace(item)) can be removed if you instead split the string with the parameter StringSplitOptions.RemoveEmptyEntries.
If the number cannot be parsed, you could throw the exception when TryParse returns false and keep the "happy path" code to run whenever TryParse is successful.

Error handling

Since it is TryParse that is failing, you should probably throw a FormatException to indicate invalid format or ArgumentException instead of InvalidCastException to indicate invalid input parameter. Since there is no casting that is failing within the code, this may confuse other developers when debugging the code.
Stricter validation of input data, for example, to handle the case with the method being invoked with the numbers parameter set to null.

Performance

There is always things to improve in this department, however, if the method is fast enough for you, I suggest focusing on readability.

Defect

Invoking the method with a negative range where the first number is negative will not work.


if (len(f) != 2):
  while (len(f) != 2):
    num += 1
    f = factors(num)
  print (num)
else:
  print (num)

In places where you use both if and while, they can usually be collapsed into a single while. You can think of an if as a single use while. In your first if block, the final print(num) would only get executed once len(f) becomes 2, so it can just be left outside of the while loop. Which will make something like this:

while (len(f) != 2):
  num += 1
  f = factors(num)
print (num)

As for ways of speeding up, you could consider keeping a list of previous primes and only dividing by those. That will cut down on the comparisons in the factor search. It might require some prior calculation, but the next calculations will be faster.

Another thing that could help is taking steps bigger than +1 while looking for the next prime. We know that all even numbers bigger than 2 are not prime, for example, and also that all numbers divisible by 3 that are bigger than 3 are not prime. So out of every 6 numbers, only two are possibly prime. If we use a counter variable n, then 6n, 6n+2, 6n+3, and 6n+4 are definitely not prime, so you could just check 6n+1 and 6n+5. Although that would require rearranging some of your program.


Nearly Illegible Prime Number Calculator

By starting with j = 3 and incrementing j by 2 you could skip a lot of unneeded computations because it will skip even values.
Instead of using a float I would go with int. Both are 32-Bit and you won't need the floating point values.
You should let your variables have some space to breathe.

Consider

while(primes[primes.Length-1]==0){
    if(isPrime(primes,j)){
        primes[Array.IndexOf(primes,0)]=(int)j;
    }
    j++;
}

versus

while (primes[primes.Length - 1] == 0)
{
    if (isPrime(primes, j))
    {
        primes[Array.IndexOf(primes, 0)] = (int)j;
    }
    j += 2;
}

where the later is much more readable. It uses the bracing style most C# developer use as well.
Stringilate() could be improved as well by using string.Join() which would look like so

public static string Stringilate(int[] iterable)
{
    return string.Join(" ", iterable);
}

and as a side note, if you need to concatenate strings in a loop its much better to use a StringBuilder instead.
You should be consitent in your coding style (public static vs. static public).
You are using braces although they might be optional. Good choice !
Instead of a concrete type you could use var instead


Join() equivalent function for F# sequences

I am porting C# code to F# that makes use of LINQ's Join() extension method. Just as I use that in method call chains, I would of course like to have an F# function to pipe into.

I think that using Join() directly in C# is actually not that common, since query syntax is much nicer for that. And I think you should consider the same thing in F#: you already know about query expressions and join, so why not use that?

Though I understand that function call chains are much more flexible, so this might not be a good option for you.

Have you considered removing the resultSelector altogether? Tuples are not very idiomatic in C#, but they are in F#, so you might want to use them.

Since you want to copy the behavior of Enumerable.Join(), I would use that to implement your method.

When considering the order of parameters, I think you should think about what is the most natural usage. I think it's this:

outer
|> Seq.join inner (fun o -> o.OKey) (fun i -> i.IKey)

This will make the order of parameters of the function quite weird, but I think it makes the most sense this way.

Putting this all together:

let join (innerSequence : 'b seq) outerKeySelector innerKeySelector (outerSequence : 'a seq) =
    outerSequence.Join(innerSequence,
        Func<_, _>(outerKeySelector), Func<_, _>(innerKeySelector),
        fun outer inner -> (outer, inner))

(Those Func casts are necessary, I think it's because F#'s weird rules for implicit casting from lambdas to delegates.)


Rearranging numbers to get the largest number

while (num != 0) {
    if (num == 0) {
        break;
    }

That if is redundant and can be removed.

Using a StringBuilder for largestNumber is roughly twice as fast on my machine.

Avoiding strings altogether is faster still:

int largestNumber = 0;
for (int i = 9; i >= 0; i--) {
  for (int j = 0; j < times[i]; j++) {
    largestNumber = largestNumber * 10 + i;
  }
}
return largestNumber;

You might want to return a long instead of an int so that, for example, largestNumber(Integer.MAX_VALUE) returns 8776444321, as expected.


Validate if either or both of two fields has been provided, as a ValidationAttribute

Fields and properties are different things. You are mixing them up: the naming in the attribute code suggests that you want to operate on fields, but the use site is supplying property names. The naming of field1 and field2 should be changed to propertyName1 and propertyName2 respectively.

Don't forget your BindingFlags! Right now your code will look up any public property with the given name, including static properties. You probably only want public instance properties:

var property1 = validationContext.ObjectType.GetProperty(_field1, BindingFlags.Instance | BindingFlags.Public);

Depending on your performance constraints, reflection might be too slow for you. If so, it's common practice to cache the results of calls to GetProperty since that information is unchanging at runtime.

It's good practice to use nameof for getting string representations of identifiers, because if SomeModel.A gets renamed then the program won't compile until you also update the attribute argument.

[EitherRequired(nameof(A), nameof(B))]
public class SomeModel
{
    public int? A {get; set;}
    public int? B {get; set;}
}


There are several problems with your code right now.

Don't create global variables. nextIndex and prevIndex are both globals that are implicitly created when you first assign to them.
Don't abuse not using braces on if statements. It is fine to skip them for a very simple statement (assuming it is allowed in your style guide) but nesting multiple ifs without braces is a recipe for disaster.

// Much safer
if (slider.getAttribute("src") == item) {
  if(index != images.length-1)
    nextIndex = index+1;
  else
   nextIndex = 0;
}

Don't use setAttribute / getAttribute if you are accessing a standard property on an element. slider.src is shorter and easier to read than slider.getAttribute('src').
Consider making your code more modular. What happens if you now want two sliders on the page? Ideally, it should just be another line of code to add the functionality (or maybe even no more lines of code!)
Consider preloading images. TimSparrow mentioned this in the comments - with your current code the next image won't be loaded until the user clicks on the next button. This can result in a bad experience on slow connections.

There are a few more things I could say, but I believe it would be more helpful to just provide an alternative implementation.

This implementation has a couple advantages:

You can just add another image-slider div wherever you want another set of images.
By using an internal hidden div for storing the images, you automatically get preloaded images.

function createSlider(container) {
  const images = container.querySelectorAll('.images > img');

  const displayImage = container.querySelector('[data-display]')

  // State
  let imageIndex;

  function setImage(index) {
    imageIndex = index;
    displayImage.src = images[index].src;
  }

  // Show the first image initially
  setImage(0);

  // Button listener
  container.addEventListener('click', event => {
    if (event.target.hasAttribute('data-prev')) {
      setImage(imageIndex === 0 ? images.length - 1 : imageIndex - 1)
    } else if (event.target.hasAttribute('data-next')) {
      setImage(imageIndex === images.length - 1 ? 0 : imageIndex + 1)
    }
  });
}

document.querySelectorAll('.image-slider').forEach(createSlider);
.image-slider .images {
  display: none;
}

  <button data-prev>Prev</button>

  <button data-next>Next</button>


I'm concentration on performance as it's the sole reason for the existence of StringBuilder (otherwise a String would do).

private List<Character> characterBuffer;

This is obviously very inefficient. List is fine, but converting every char in  Character surely is not. The memory consumption is bad, too, namely 4 or 8 bytes (depending on using compressed oops) for the reference and 0 or 8 bytes for the object (0 if it's a cached Character, i.e., ASCII). So you need 4 to 16 bytes per char instead of 2.

public StringBuilder() {
    characterBuffer = new ArrayList<Character>();
}

This should be done in the initializer.

if(anotherString != null) {

There should be a space after if. Silently ignoring null is strange (not that appending "null" would be any better).

char[] charArray = anotherString.toCharArray();

This is needlessly inefficient as you're creating a throw-away charArray while you can use anotherString.charAt instead.

An interesting approach would be to collect the given strings instead. If your string builder gets fed mostly with strings, collecting them as they come could be better than flattening them into a single char[]. While this would make some operations (e.g., delete) pretty complicated, it could be pretty efficient for the most important operations.

  I suggested using a primitive char array buffer that can grow if there is an overflow.

That's the standard approach.

private int curIndex;

Let's call it length as it's what length() returns.

public StringBuilder() {
    characterBuffer = new char[5];
    curIndex = 0;
}

The former belongs to the initializer, the latter belongs nowhere (it's the default).

if(overflow(charArrayLength)) {

A method checking for overflow is fine, but a method handling it would be better.

private int newLength(int arrayLength) {
    return (characterBuffer.length + arrayLength) + 10;
}

No! You'll be resizing too often. Imagine appending "0123456789A" in a loop. Every single append will copy the whole buffer, more and more characters... complexity \$O(n^2)\$.

What you need is an exponential growth. Something like

2 * characterBuffer.length + arrayLength + 10;

or

characterBuffer.length + (characterBuffer.length >> 1) + arrayLength + 10;

if you want a growth factor of 1.5.

private boolean overflow(int arrayLength) {
    return (arrayLength + curIndex) > characterBuffer.length;
}

Needless parens. I guess, it should read >=.


Integer to Alphabet string ("A", "B", ...."Z", "AA", "AB"...)

Math! Simple math is certainly the nicest way, no lists to deal with, just old fashion ASCII and math. If you want to be able to toggle the capitalization of this method, simply use a ternary operator like this isCapital ? 'A' : 'a' I just left it capital as that is how the OP seemed to want it. Jeff Mercado's Answer explained well enough the differences between calculated, recursive and such... I mostly wanted to provide a simplistic calculated answer that did not involve using lists.

public static string IntToLetters(int value)
{
    string result = string.Empty;
    while (--value >= 0)
    {
        result = (char)('A' + value % 26 ) + result;
        value /= 26;
    }
    return result;
}

Edit: To meet the requirement of A being 1 instead of 0, I've added -- to the while loop condition, and removed the value-- from the end of the loop, if anyone wants this to be 0 for their own purposes, you can reverse the changes, or simply add value++; at the beginning of the entire method.


I've reviewed your code and here's what I've found.

Reconsider your algorithm

It's not really necessary to iterate through all of the characters in the string, as the current code does.  Since the task is to find only the first non-repeated character, the algorithm can terminate as soon as it finds a non-repeated character.  A simple way to do that is this:

void findNonRepeatedChar( const std::string& record )
{
    for (std::string::size_type i = 0; i < record.size(); ++i) {
        if (record.rfind(record[i]) == i) {
            if (record.find(record[i]) == i) {
                std::cout << record[i] << '\n';
                return;
            }
        }
    }
}

Reconsider the interface

It is odd that a function named findNonRepeatedChar() does not actually return anything.  The code could be clearer if it actually returned the non-repeated letter and left the printing to the calling routine.

Don't instantiate an object that is not needed

There is no reason to instantiate the record to "tooth" (or any other value) within readInputFile.

Use more descriptive function names

The function named readInputFile does more than simply read the file and as mentioned before, the findNonRepeatedChar() function doesn't return anything but prints as a side effect.  I'd be inclined to omit readInputFile entirely, and put its contents within main and to change the interface to as previously mentioned.

Give the user useful help

The program is probably not really named program_name so the string that's printed if there aren't enough commmand line arguments should probably instead be:

std::cout << "Usage: " << argv[0] << " input_file_name\n";


First impressions matter in interview coding situations.  My first thought is: There's a lot of code.  And interviewers usually don't like to wade through a lot of code.  For you, as a candidate, that may be a sign that you are taking the wrong approach.

Function names should be lower_case_with_underscores as specified in PEP 8 coding conventions.

There should be a function that accepts a string and returns either True or False.  Your brokenRecord() function…

def brokenRecord(sent):
   if sent == "": # Use defualt string if empty
      sent = "This is a a is This"
   print("Determining if broken record: %s" % sent)
   …
   print("Not a broken record.")

… incorporates all kinds of junk that make it not reusable:

A weird if sent == "": sent = "This is a a is This" special case.  Such
a special case should be moved out into your testing mechanism — the caller, or, better yet, a doctest.
Printing diagnostics.  Again, such code should be done by the caller.
Not returning any useful value, making it hard for the caller to know what happened.

Catching IndexError to recover from out-of-bounds array access is poor style.

In your main loop, you could eliminate the break by swapping the try and while.

# do until ctrl+c
try:
   while True:
      brokenRecord(raw_input("\nString: "))
except KeyboardInterrupt:
   print("\nThanks for testing!")

Suggested solution

If I, as an interviewer, had asked this question, I would be hoping for a completely different kind of answer.  String analysis is much more easily done using regular expressions.  In particular, you need this feature:

  Backreferences in a pattern allow you to specify that the contents of an earlier capturing group must also be found at the current location in the string. For example, \1 will succeed if the exact contents of group 1 can be found at the current position, and fails otherwise. Remember that Python’s string literals also use a backslash followed by numbers to allow including arbitrary characters in a string, so be sure to use a raw string when incorporating backreferences in a RE.

  For example, the following RE detects doubled words in a string.

>>>
>>> p = re.compile(r'(\b\w+)\s+\1')
>>> p.search('Paris in the the spring').group()
'the the'

import re

def is_broken_record(s):
    """
    Check whether a string contains sequential repeated substrings.

    >>> is_broken_record("This is is a broken record")
    True
    >>> is_broken_record("This is a is a broken record")
    True
    >>> is_broken_record("This is a broken record. This is a broken record.")
    True

    >>> is_broken_record("This is not is a broken record")
    False
    >>> is_broken_record("This is a is This")
    False
    >>> is_broken_record("This is a broken record. This is not a broken record.")
    False
    """
    return bool(re.search(r'\b(.+)\s+\1', s))


Given a string, return n distinct characters with their respective counts, as well as the remainder of the string

I would avoid using indexes altogether and rely on iter to advance character by character and remember what's left in the string:

def enc_consume(carrier, nsyms):
    characters = defaultdict(int)
    stream = iter(carrier)

    for char in stream:
        characters[char] += 1
        if len(characters) >= nsyms:
             break

    return characters, ''.join(stream)


Is there a better way to walk a directory tree?

You might be interested in the concept of iteratees/pipes that can be used to solve this problem. It allows you to separate producing the tree and consuming it somewhere else without direct callback functions: You create a producer that enumerates the directory tree, perhaps some filters that modify the data and a separate consumer that works on the data. And then compose and run the whole pipeline. See also Streaming recursive descent of a directory in Haskell.

There are also specialized Haskell packages for that such as directory-tree, which you can use or study.

Edit: As an example I reworked your code using conduit. This library (and others based on the same principle) has several advantages, namely:

It separates the producer of the data with its consumer.
In a source you just call yield when you want to send a piece of data to the pipe.
In a sink you call await whenever you want to receive a piece of data (here we used more specialized awaitForever).
You can have conduits that sit in the middle and consume and produce values at the same time. They can do whatever processing on the stream, mixing calls to yield and await as they wish.
This allows you to create complex computation where the behavior of your components depends on data sent/deceived earlier. We use this in our source (traversing a directory tree), and I also added it to the sink (visitor) - it keeps track of how many directories it has been passed so far.
Both source and sink (and intermediate conduits, if any) can have finalizers.

Some suggestions:

Create your own data types instead of using combinations of Either and (,). It makes your code shorter and easier to understand.
Sometimes it's worth declaring new functions instead of using complex case ... of expressions. It can make code easier to read.
hlint can suggest how to (syntactically) improve a piece of code.

import System.FilePath ((</>))
import Control.Monad (filterM, forM_, return)
import System.IO.Error (tryIOError, IOError)
import System.Directory (getDirectoryContents, doesFileExist, doesDirectoryExist)
import Control.Monad.Trans.Class (lift)
import Data.Conduit

data DirContent = DirList [FilePath] [FilePath]
                | DirError IOError
data DirData = DirData FilePath DirContent

-- Produces directory data
walk :: FilePath -> Source IO DirData
walk path = do
    result <- lift $ tryIOError listdir
    case result of
        Right dl@(DirList subdirs files)
            -> do
                yield (DirData path dl)
                forM_ subdirs (walk . (path </>))
        Left error
            -> yield (DirData path (DirError error))

  where
    listdir = do
        entries <- getDirectoryContents path >>= filterHidden
        subdirs <- filterM isDir entries
        files <- filterM isFile entries
        return $ DirList subdirs files
        where
            isFile entry = doesFileExist (path </> entry)
            isDir entry = doesDirectoryExist (path </> entry)
            filterHidden paths = return $ filter (\path -> head path /= '.') paths

-- Consume directories
myVisitor :: Sink DirData IO ()
myVisitor = addCleanup (\_ -> putStrLn "Finished.") $ loop 1
  where
    loop n = do
        lift $ putStrLn $ ">> " ++ show n ++ ". directory visited:"
        r <- await
        case r of
            Nothing     -> return ()
            Just r      -> lift (process r) >> loop (n + 1)
    process (DirData path (DirError error)) = do
        putStrLn $ "I've tried to look in " ++ path ++ "."
        putStrLn $ "\tThere was an error: "
        putStrLn $ "\t\t" ++ show error

    process (DirData path (DirList dirs files)) = do
        putStrLn $ "I've looked in " ++ path ++ "."
        putStrLn $ "\tThere was " ++ show (length dirs) ++ " directorie(s) and " ++ show (length files) ++ " file(s):"
        forM_ (dirs ++ files) (putStrLn . ("\t\t- " ++))

main :: IO ()
main = do
    walk "/tmp" $$ myVisitor


Program that finds the stretch factor of a parabola

This is fairly straightforward. Good work on separating out the user input into its own function! Here are some things that could use improvement:
Don't Use Pointers for Values
In your pwidth() function, you aren't changing the value of any of the arguments. They should be passed by value since they are simple types. You could even make them const to clarify that the function does not change them. (Some would say that's overkill for plain-old-datatypes. It's up to you.)
In general, in C++, it's better to use references than pointers because they are safer. But in both cases, you usually use a reference or pointer either when the value will be changed by the function, or in cases where the data is too large to pass on the stack. (You can use a const in the case where the data is too large to pass on the stack but won't change in the function.) The cstor reference in gcin() is great!
Naming
I think your names could be improved. pwidth and gcin don't mean anything to me. If pwidth() is calculating the "stretch factor", then call it stretch_factor() or something along those lines. (Or if the p stands for "parabola" just name it parabola_width().) I think gcin() would be better named something like prompt_user(), or get_user_input(), or get_int_from_user().
Likewise with variable names. px, vx, etc. should be point_x, vertex_x, etc. It's much easier to read.
Avoid using namespace std
This Stack Overflow question lays out why using namespace std is a bad idea.
Optimization
In your pwidth() function, you're calling the pow() function. That's a really expensive function. For the main() that you've written, it won't make much difference, but if you ever need to use pwidth() in time-critical code, that could become a bottleneck. Since all you're doing is squaring a value, I'd rewrite it like this:
float pwidth(int *vx, int *vy, int *px, int *py) {
    float delta_x = (*px - *vx);
    return (*py - *vy) / (delta_x * delta_x);
}

Why is that the case? Doing it locally is a single machine instruction - a multiply. Calling the pow() function involves first jumping to the code for the function, then doing some math, then jumping back to your code to finish up. Some of that may be hidden by the pipelining, but the math of the pow() function is also more complicated than a single instruction. You can test it for yourself by writing a loop like this and timing it:
float x = 1.2345678;
float sum = 0.0;
for (int i = 0; i < 10000000; ++i)
{
    sum += pow(x, 2.0);
}

Then do it again like, this:
float x = 1.2345678;
float sum = 0.0;
for (int i = 0; i < 10000000; ++i)
{
    sum += x * x;
}

(Just be careful that your compiler doesn't optimize away any of the loop when testing!)


API Client: Querying data out of an endpoint

In the request method the exception variable really doesn't have to
be set before using it, just inline it and make the code more succinct:

def request(self, endpoint, params=None):
    response = self.session.get(endpoint, timeout=TIMEOUT, params=params)
    res_code = response.status_code
    if res_code != API_OK:
        raise API_ERRORS[res_code]
    return response.json()

Also, I'm guessing API_ERRORS[res_code] will also work and be more
expected for any reader.

In the query_match method res doesn't have to be initialised, that's
not pythonic actually:

def query_match(self, match_id, shard='default'):
    url = f'{SHARD_URL}/{shard}/matches/{match_id}'
    return Match(self.request(url))

The process_matches method could be a bit simpler:

def process_matches(self, list_matches):
    ret = []
    for m_i in list_matches:
        ret.append(build_json(self.query_match(m_id)))
    mongo.insert_many('matches', ret)

Or, there's the option to go for a less imperative list comprehension
too:

def process_matches(self, list_matches):
    ret = [build_json(self.query_match(m_id))
           for m_i in list_matches]]
    mongo.insert_many('matches', ret)

Regarding your second question, if I read it right, no, not a good idea
from what I can tell from the code, leaving Match as a pure data
object will serve you better in the long run.  It's better if the two
responsibilities aren't mixed.  It'll also make it more clear what's
being tested in your test cases if you can clearly distinguish between
something that just holds the data and a API client (wrapper) that does
networking (for example).


Avoid using namespace std

This can cause name collisions because it adds every name in the std namespace to the global namespace. For a small program like this one it's unlikely that you'll run into any problems (then again, maybe not) but it's best to get into the habit of using the std:: prefix on names in the std namespace.

Alternatively, you can introduce using declarations like using std::cout; to add specific names to the global namespace.

Avoid std::endl in favor of \n

std::endl flushes the stream, which can cause a loss in performance.

Declare variables in the most local scope possible

You declare num at the beginning of mult() but you don't actually use it (and initialize it to 0) until you're inside the j loop. It's better to simply declare and initialize it in the same place and in the place where you start to use it.

I would also rename it to be more descriptive (e.g. sum or dot_product).

Avoid hard-coded numbers

Your code works with \$4\times 4\$ matrices but you've got 4 hard-coded all over the place. You say

  This can easily be generalized for any nxn matrix by replacing 4 with any positive number greater than 1.

But there are a lot of instances where 4 needs to be replaced. At the very minimum you should define 4 as a constant and use that constant in the code:

const std::size_t N = 4; // or constexpr instead of const if your compiler supports it

int mult(int A[N][N], int B[N][N]) {
    int C[N][N];

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            int num = 0;
            for (int k = 0; k < N; k++) {
                num += A[i][k] * B[k][j];
            }
            C[i][j] = num;
            std::cout << num << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

Now I just need to change the definition of N once to use a number other than 4.

Use static_assert to enforce the condition that \$N > 1\$

If your compiler supports static_assert you can ensure that \$N > 1\$ at compile time and cause a compilation failure with a simple message to explain the problem.

Function template

The multiplication algorithm is basically the same for any \$N > 1\$, so this function is a good candidate for a function template based on the dimension \$N\$. For example, you have A with N = 4, but in the same program you could have a matrix (2D array) D with N = 3 and the same code is used to multiply with both matrices. Here's a demo using a function template:

#include <iostream>
#include <string>

template<std::size_t N>
int mult(int A[N][N], int B[N][N]) {
    static_assert(N > 1, "N must be greater than 1");

    int C[N][N];

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            int num = 0;
            for (int k = 0; k < N; k++) {
                num += A[i][k] * B[k][j];
            }
            C[i][j] = num;
            std::cout << num << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

int main() {
    const std::size_t N = 4;
    int A[N][N];
    int ind = 0;
    std::cout << "Default Matrix A: \n \n";

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            A[i][j] = ind; ind++;
            std::cout << A[i][j] << " ";
        }
        std::cout << std::endl;
    }
    std::cout << "\nMultiplication of A^2: \n \n";
    mult<N>(A, A);

    const std::size_t N2 = 3;
    int D[N2][N2];
    ind = 0;
    std::cout << "\nDefault Matrix D: \n \n";

    for (int i = 0; i < N2; i++) {
        for (int j = 0; j < N2; j++) {
            D[i][j] = ind; ind++;
            std::cout << D[i][j] << " ";
        }
        std::cout << std::endl;
    }
    std::cout << "\nMultiplication of D^2: \n \n";
    mult<N2>(D, D);
    return 0;
}

Consider a Matrix class instead of 2D arrays

Mathematical libraries implement matrices as a class. Internally, the Matrix class may use 2D arrays to store the data, but client code shouldn't depend on how that data is stored. A Matrix class can hide the implementation details from client code.

Extend to non-square matrices

In general, an \$N \times M\$ matrix \$A\$ can be multiplied with a matrix \$B\$ if \$B\$ is \$M \times P\$ (\$A\$ has \$M\$ columns and \$B\$ has \$M\$ rows, but otherwise the two matrices can have different dimensions). With a function template you can easily extend the multiplication function to support non-square matrices. Simply add the necessary template arguments and tweak the algorithm to use dimensions other than N. Here's a demo:

#include <iostream>
#include <string>

template<std::size_t N, std::size_t M, std::size_t P>
int mult(int A[N][M], int B[M][P]) {
    static_assert(N > 1, "N must be greater than 1");
    static_assert(M > 1, "M must be greater than 1");
    static_assert(P > 1, "P must be greater than 1");

    int C[N][P];

    for (int n = 0; n < N; n++) {
        for (int p = 0; p < P; p++) {
            int num = 0;
            for (int m = 0; m < M; m++) {
                num += A[n][m] * B[m][p];
            }
            C[n][p] = num;
            std::cout << num << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

int main() {
    int A[4][3]{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
        {10, 11, 12}
    };

    int B[3][2]{
        {1, 2},
        {3, 4},
        {5, 6}
    };

    mult<4, 3, 2>(A, B);
    return 0;
}

The demo program outputs the \$N \times P\$ (\$4 \times 2\$) matrix product:

22 28
49 64
76 100
103 136


Parsing comma-separated floats and semicolon-delimited commands

Two-dimesional array

Your first function can be aggressively reduced by replacing cI and friends by a 2D array:

float *Receiver::parse_pid_substr(char* buffer) {
  static float pids[8];
  memset(pids, 0, 8*sizeof(float) );

  char rgcPIDS[8][32];
  size_t i = 0, c = 0, p = 0;
  for(; i < strlen(buffer); i++) {
    if(buffer[i] == '\0') {
      break;
    }
    else if(buffer[i] != ',') {
      rgcPIDS[p][c] = buffer[i];
      rgcPIDS[p][c+1] = '\0';
      c++;
    } else {
      p++;
      c = 0;
      continue;
    }
  }

  for (int j = 0 ; j < 8 ; ++j) {
    pids[j] = atof(chars[j]);
  }

  return pids;
}

continue

In the following piece of code:

} else {
  p++;
  c = 0;
  continue;
}

The else clause is the last of your loop, and continue is the last instruction of that clause. You can remove continue: even without it, your function will still work and behave the same way as before.

Zero-initialization

Instead of using memset to zero-initialize your arrays, you can use the language zero-initialization for arrays whose bound is known at compile-time:

char rgcPIDS[8][32] = { 0 };

Names

The names you use are all but explicit. While i is good as a loop iterator, c and p should have more explicit names.

NOTE: Hadn't it been for the Receiver::, I would have thought that your code was written in plain old C, and not in C++. Is it intentional?


Create a GUI to update parameters of an Object

I see a couple potential issues with the code beside the duplication of code in focus listeners that you mention:

you treat the text the user typed into a text field as a key of map that contains the Gobs without checking if such key exists - what will happen when the user types a nonexisting key?
the name of the texfield that identifies the Gob (gobNumber) indicates that the gob is identified by a numerical value, yet the key of the map is a String. Either a numerical value should be used as the key of the map or the textfield could be renamed to avoid the confusion

To deal with the duplication - a basic way of generalizing the focus listeners would be to use the Template method pattern. You could extract the code that would be duplicated for each listener to an abstract class and then delegate the parts that would be different to a specific subclass.

public abstract class UpdateGobFocusListener implements FocusListener
{
    private final Map<String, Glob> globs;
    private final JTextField globNumberTextField;

    public UpdateGobFocusListener(Map<String, Glob> globs, JTextField globNumberTextField)
    {
        this.globs = globs;
        this.globNumberTextField = globNumberTextField;
    }

    public void focusGained(FocusEvent e)
    {

    }

    public void focusLost(FocusEvent e)
    {
        Glob glob = globs.get(globNumberTextField.getText());
        updateGlob(glob);
    }

    protected abstract void updateGlob(Glob glob);

}

And an example of a subclass:

public class DateGlobUpdater extends UpdateGobFocusListener
{

    private final JTextField dateTextField;

    public DateGlobUpdater(JTextField dateTextField, Map<String, Glob> globs, JTextField globNumberTextField)
    {
        super(globs, globNumberTextField);
        this.dateTextField = dateTextField;
    }

    @Override
    protected void updateGlob(Glob glob)
    {
        glob.date = dateTextField.getText();
    }

}

Alternatively, if you prefer Composition over inheritance, you could extract the duplicated code to a general focus listener, create a GobUpdater interface and then move the different parts to a separate implementation of the interface each. The general focus listener could be injected with the specific implementation through a constructor.


I'll give you some hints/comments:

factorise(factor) == [1, factor] or factorise(factor) calculates factorise(factor) twice, consider saving its result as a variable and re-using it instead of incurring the cost twice.
You're treating 1 as a special case (in factorise(factor) == [1]), but it isn't. 1 can be factored into anything, but should not be considered a prime factor. Why? Because 1 isn't a prime.
I think your algorithm might be slightly off. For example, if I say prime_factorise(8) I get [1, 2], but I believe the answer should be [2, 2, 2] since 2 is prime, and 2*2*2 = 8.
Overall, my biggest hint would be try to improve your algorithm by thinking of the operation as a reduction from some number, into its prime factors. Think _how can I transform num_to_prime_factorize into a list of its prime factors ("transform" being key).

I don't want to give away the answer, so, hopefully these tips will suffice to get you in the right direction.


Get sum of an array in 3 ways, for, while and recursive

You may already know the following Perl 6 tidbits, but for others reading along:

The ordinary OO way to express the sum of a list of numbers in a variable list is list.sum;
The ordinary functional way to express the same thing is sum list;
A less common functional idiom that produces the same result is [+] list which is a reduction.

Imo your code is fine. That said:

Parentheses are frequently optional

Larry often pipes up about what he calls "superstitious parens". More generally I think there's a rough consensus among Perl 6 folk that readability for most folk is best served by omitting optional parentheses when the meaning remains clear without them. This is almost always true around conditional expressions. I generally omit them around argument lists too. If I were writing the code you've written I'd likely have dropped seven pairs of "superstitious parens" thus:

sub sumFor(@list)
{
   my $sum = 0;
   for @list
   {
      $sum += $_;
   }
   return $sum;
}

sub sumWhile(@list)
{
   my $sum = 0;
   my $index = 0;
   while $index < @list.elems
   {
      $sum += @list[$index++];
   }
   return $sum;
}

sub sumRec(@list, $index = 0)
{
   my $sum = 0;
   if $index < @list.elems
   {
      $sum = @list[$index] + sumRec @list,$index+1;
   }
   return $sum;
}

my @list = 1,2,3,4;

say sumFor @list;
say sumWhile @list;
say sumRec @list;

Sigils are frequently optional

I don't know of any emerging consensus about use of sigil'd variables vs non-sigil'd variables but you can slash sigils like this:

sub sumRec(\list, \index = 0)
{
   my $sum = 0;
   if index < list.elems
   {
      $sum = list[index] + sumRec(list,index+1);
   }
   return $sum;
}

Stronger typing

Most built in operations accept arguments of a wide range of types and automatically coerce them to fit the operation. This highly generic approach is considered a strength. Thus, for example:

say sum '21', '21'; # 42

This genericity is the default in Perl 6 code. But sometimes you may prefer to explicitly specify types. Thus, perhaps:

subset NumericList of List where .all ~~ Numeric;

sub sumFor(NumericList \list )
{
   my $sum = 0;
   for list
   {
      $sum += $_;
   }
   return $sum;
}

my \list = 1,2,3,4,'a';
say sumFor list; # "Constraint type check failed..."


Calculate min, max, mean and median out of array Version 2

To add to Peter's answer:

I can only think of one case where you couldn't compute a valid result (min, median, max, mean) for an array and that's when the array is empty (or infinite I suppose, but if that's a problem for you please let me know where you buy your RAM). Since this is trivial to check I would generally leave it up to the caller to do so (and document that expectation in the function's interface). It's just simpler and cleaner.

I have some minor style suggestions:

I advise against using assertions for error checking (except for during debugging). Assertion failures cause your program to immediately terminate. In general you would probably want to propagate errors back up the call stack so that the caller can handle them (hopefully) gracefully.
You check if len is less than zero, but this can't occur as len has an unsigned type.
It makes sense to check len before allocating calc_array. In general, if you are checking parameters you generally want to do it at the beginning of a function. It's more readable and may save you work.
I generally prefer to use the types defined in stdint.h when reasonable (uint32_t, uint64_t etc.).


Optimizing quicksort partition method/function for duplicate elements

Naming

I'm a stickler for variable naming - most of my answers mention it. You should be too - correctly named variables make code much easier to maintain.

Now, while I don't know C that well at all, the principles are the same. In your first three lines you do this:

int partition(int ar[], int lft, int rgt) {
int left = lft;
int right = rgt;

Why bother with the extra two declarations? Name the variables correctly in the method declaration, and you can eliminate them entirely. While we're here, what does ar mean? You should name your variables according to the data they hold, so perhaps a method declaration like this would be better:

int partition(int unsortedArray[], int leftIndex, int rightIndex)

Then update your variable references in the rest of the code.

Formatting

Indent your code correctly. Trust me, it makes it much easier to see what comes in which block. I don't know whether this was a product of how you pasted it into the question (which it might well be), but make sure your method code is indented from the declaration.

Sorting algorithms

There are four major sorting algorithms:

Bubble sort
Shuttle sort
Quicksort
Shell sort

Each of those is useful for a different purpose, and each has a different time complexity. If you read through the Wikipedia articles (links above) for each, you should at least have a basic grounding in each.


Performance of dynamic Fibonacci generator and dead rabbits

With regard to your time complexity:

With your calculation of the nth Fibonacci number, you could do it in \$O(1)\$ time by using the relation:

$$F_n = \left\lfloor \frac{\varphi^n}{\sqrt{5}} + \frac{1}{2} \right\rfloor$$

So the 484th Fibonacci number would be equal to:

$$\left\lfloor \frac{\varphi^{484}}{\sqrt{5}} + \frac{1}{2} \right\rfloor \approx 6.317 \times 10^{100}$$

If you do not want to use the floor function, you can achieve the exact same result by manipulating the equation and using the nearest-integer function: \$\left[\frac{\varphi^n}{\sqrt5}\right]\$

This will speed up your program if you intend on calculating very large Fibonacci numbers.

Note: when calculating \$\varphi^n\$, use math.pow(x,y) because it uses floating point exponentiation and is always \$O(1)\$, whereas pow(x,y) and x**y can vary. For calculating \$\varphi\$ itself, there are many methods, here is an example.


Using this.r to represent elapsed time is highly unconventional.  I would have guessed that r stood for "radius".  Why not use this.t like a sane programmer?

The draw() function ends with this.r += 2;, which is odd.  Why should the drawing routine manage the passage of time?  I would expect the time to be managed either in reference to the wall clock or to be passed in as a parameter by whatever code calls draw().

These don't look like parabolas to me.  At best, they would be degenerate ones, since this.x never changes.

The placement of the closing brace here:

if(this.y < 0) {
    this.r = 0;}

is weird.  Conventional formatting would be:

if (this.y < 0) {
    this.r = 0;
}


Separate business logic from Data Access Logic in the repository

First of all I'd say that your foreach loop will never loop, because it is only reached when there are no elements in existingLowerSchoolclasses.

In general I would recommend to re-think your datastructure, especially with a view towards next year and the year after. Because then you'll wish you had identified classes like "English 8 c 2014" or "Math 7 d 2015".

This will make it easier to enforce the constraints you described.

If you're concerned about the number of queries you could use a stored transaction. Even that feels old-fashioned, in some cases it still makes sense to guard the access to N:M relations with those things. The question is always: Is it really a domain problem, or is it caused by the fact that your data structure doesn't adhere enough to the domain? If you can answer that, you'll know where to put the Data Access Logic.

Last of all let me be honest: Whenever I see a N:M relation I get very suspicious about it. In most real-world situations, there are no anonymous N:M relations. A student started a class at a certain time and left it at another, also different students could have different mentors within one course, and there might be much more attributes you might want to assign to that relationship in the future. Therefore I would advise you to remodel this relation, e.g. by introducing a ClassMembership entity.


As you define efficient to be "less lines of code", here it is:

function moveIt(){
    var textToInsert = '';
    var textLength = 10;

    for (var i = 0; i <= textLength; i++)
        textToInsert+= (i==position)?'[-]':'-';
    (position==textLength)?position=0:position++;
    divToEdit.innerHTML = textToInsert;
}

Demo: http://jsfiddle.net/YsjLp/3/


Passing an int with the ref keyword does not involve any boxing at all. Do not confuse this with "passing an int by reference" (as in, a function with return type Object returning an int,) which is quite a different thing, and it does involve boxing.

Your code seems quite efficient to me, I have nothing to comment on.


Transpose 2D Matrix in Java - Time & Space Complexity?

I have three suggestions for you.

Instead of String, you can use char, less memory footprint than a String.
In the transpose method, I suggest that you return the array, since the method does nothing at the moment.

static char[][] matrix = {
   {'a', 'L', 'M', 'd'},
   {'b', 'G', 'c', 'N'},
   {'H', 'K', 'e', 'F'},
   {'I', 'J', 'O', 'P'}
};

public char[][] transpose(char[][] matrix) {
   char[][] transposedArray = new char [4][4];

   for (int row = 0; row < 4; row ++) {
      for (int col = 0; col < 4; col++) {
         transposedArray[row][col] = matrix[col][row];
      }
   }

   return transposedArray;
}

Since the matrix variable is static, I suggest that you also put the method static.

Refactored code

public static void main(String[] args) {
   System.out.println(Arrays.deepToString(transpose(matrix)));
}

static char[][] matrix = {
   {'a', 'L', 'M', 'd'},
   {'b', 'G', 'c', 'N'},
   {'H', 'K', 'e', 'F'},
   {'I', 'J', 'O', 'P'}
};

public static char[][] transpose(char[][] matrix) {
   char[][] transposedArray = new char [4][4];

   for (int row = 0; row < 4; row ++) {
      for (int col = 0; col < 4; col++) {
         transposedArray[row][col] = matrix[col][row];
      }
   }

   return transposedArray;
}


I'm not sure of the lua syntax but something like

arrayAllFalse=TRUE;
for element in array
  if (element) then
  arrayAllFalse=FALSE
  end

if (arrayALLFalse) then
    --something
end


Comma delimited string from list of items

Would this not suffice?

private string ConcatenateCheckBoxListItems()
{
    return string.Join(", ", from item in MyList select item.Value);
}


func getLineArrayFromFile(fileName: String) throws -> Array<String>

The function does not get lines from an arbitrary file, but from a resource file.
The "get" prefix is usually not used in Objective-C or Swift.
Array<String> can be shortened to [String].

So my suggestion for the function name would be

func linesFromResource(fileName: String) throws -> [String]

let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)
if path == nil {
    throw ImportError.FileNotFound
}

As you are obviously using Swift 2, this can be simplified with the guard
statement. Note that path is no longer an optional.
There are pre-defined NSError codes which can be used here instead of
defining your own. This also gives better error descriptions for free.

Example:

guard let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil) else {
    throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [ NSFilePathErrorKey : fileName ])
}

do {
    let content = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
    lineArray = content.componentsSeparatedByString("\n")
} catch {
    throw ImportError.CouldntGetArray
}

You are catching the error and throw your own error code in the failure case,
so the actual error information is lost.
Better just call the try String(..) and let an error propagate to the
caller of your function:

let content = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)

Again, this gives better error descriptions for free.

So the complete method would now look like this (no optionals anymore,
no forced unwrapping with !):

func linesFromResource(fileName: String) throws -> [String] {

    guard let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil) else {
        throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [ NSFilePathErrorKey : fileName ])
    }
    let content = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
    return content.componentsSeparatedByString("\n")
}

And a typical usage would be

do {
    let lines = try linesFromResource("file.txt")
    print(lines)
} catch let error as NSError {
    print(error.localizedDescription)
} catch let error {
    print(error)
}

The reason for the final catch let error is that it is required that the catch statements are exhaustive.
Even if we know that the function throws only NSErrors, the compiler doesn't know
that. (There are exceptions but that is a different topic .)

Now to your question how an error should be handled in general, and I would
say: it depends. There are tree different scenarios:

Loading the strings can fail, and you want to present or log an error message
in that case. Then the above method of throwing and catching an error is appropriate.
Loading the strings can fail, but the particular reason is of no interest
to the caller. In that case I would change the function to return an optional.

Example:

func linesFromResource(fileName: String) -> [String]? {

    guard let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil) else {
        return nil
    }
    do {
        let content = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
        return content.componentsSeparatedByString("\n")
    } catch {
        return nil
    }
}

 // Usage:
if let lines = linesFromResource("file.txt") {
    print(lines)
}

Finally, if failing to load the strings is a programming error then the function should abort in
the error case, and return the (non-optional) strings otherwise.

As an example, if this function is only used to load strings from fixed compiled-in
resource files which are supposed to exist, then failing to load a file would
be a programming error and should be detected early:

func linesFromResource(fileName: String) -> [String] {

    guard let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil) else {
        fatalError("Resource file for \(fileName) not found.")
    }
    do {
        let content = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
        return content.componentsSeparatedByString("\n")
    } catch let error {
        fatalError("Could not load strings from \(path): \(error).")
    }
}

let lines = linesFromResource("file.txt")
print(lines)

fatalError() prints a message before stopping execution of the program, which can
be helpful to locate the programming error. Otherwise you could shorten the
"forced" version to

func linesFromResourceForced(fileName: String) -> [String] {

    let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)!
    let content = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
    return content.componentsSeparatedByString("\n")
}

which is the "three liner" that you were looking for in the introduction to
your question.


Makefile to build and debug a C++ console app

Making sources?

The line

all: $(SOURCES) $(EXECUTABLE)

asks make to build $(SOURCES), in this case helloWorld.cpp. Is it possible to build it? Strictly speaking there are situations when you do want to build the source file (e.g. fetch it from git/cvs/sccs) but it is not applicable here: no rule is provided. Generally you don't want to build something which doesn't depend on anything. In any case, let make deduce; this is what it is good for.

all: $(EXECUTABLE)

is what you want.
Be consistent

all depends on $(EXECUTABLE), but debug depends on helloWorld. Once you defined a macro, use it everywhere.
Synonymous targets

Consider the scenario: make; ./helloWold; something goes wrong and you want to debug; make debug: everything is up to date. To have a debug build you must intervene with make clean. A good practice is to separate debug and release builds into different directories.
Automatic dependencies

In your example the .o file depends only on a corresponding .cpp. In real life the .cpp has some #includes - and the .o must depend on them all. Otherwise you will end up with an inconsistent build. Listing the .h dependencies manually is tedious and error prone. The standard practice is to let the compiler generate them automatically. For example, g++ has -MM, -MT, etc options just for this purpose:

DEPS := $(SOURCES:.cpp=.d)
.cpp.d:
    $(CC) $(CXXFLAGS) -MM -MT -o $@ $<
-include $(DEPS)

-c doesn't belong to CFLAGS

-c is typically not listed in a CFLAGS: you may want to generate various outputs (e.g. preprocessed source, assembly source, dependencies, documentation, etc) with the same set of flags. The way to achieve this is to specify -c or -MM or -S or whatever separately from other flags, e.g.

.cpp.o:
    $(CC) -c $(CFLAGS) ....

.cpp.s:
    $(CC) -S $(CFLAGS) ....

etc.
CC

Traditionally a c++ compiler is referred as CXX and uses CXXFLAGS. The CC and CFLAGS are reserved for plain c.


Honestly, I think you have it just right with your current code: simple enough, yet powerful enough.

In your case, you need to support multiple implementations of Web crawlers API. To be able to abstract your code from all those implementations, an interface needs to be introduced. This interface will define the contract that your Web crawlers will satisfy. When this interface is introduced, the rest of your code can depend on that interface only, and not on the implementation.

Right now, your contract defines a methid visit(url) that takes a URL and returns the HTML content at that URL. This could be changed at a later time (e.g. adding time-outs or error handlers) but it's a good start.

The next problem to tackle is how to use the right implementation? This is typically done by using dependency injection. To put it simply, this is a design pattern where a class lets its dependencies be injected through constructor or setters instead of constructing them itself. For your example, consider a class MyClass that would depend on a Web crawler:

public class MyClass {

    private CrawlerApiHandler crawler;

    // the crawler to use in being injected into this class
    public BodyExtractor(CrawlerApiHandler crawler) {
        this.crawler = crawler;
    }

    // later on, use crawler to do some fancy things

}

You could then centralize the real implementation in a configuration class / file. The great advantage is that you now need to define the real implementation class in a single place and the rest of the code is completely decoupled from it by just depending on the interface.


You should use newInstance() pattern, described in this link

The profit of using this pattern is, developer cannot instantiate Fragment without providing arguments. There will be no chances that you will get default value when you try to get that value. One more thing is, whatever key is required for a fragment should be defined in public static final String so that no chances for string mismatch in key.


PHP associative array with two properties

I can immediately see two more options, perhaps they're something you're after, perhaps not.
Option 1
Turn $data into a multidimensional array. You would end up with something such as:
...array('param1' => [$param1, \PDO::PARAM_STR], 'param2' => [$param2, \PDO::PARAM_STR]...

Pros

Both value data and type are paired to the key, so now you can simply refer to either with array referencing.
You can play with indentations and returns to find a format that suits you. It's easy enough to separate each key/value onto a new line.

Cons

It's more condensed, which might lead to readability issues. (Do you keep in mind the 2nd pro above though)
An IDE's autoformat might place it all on one line, depending on your settings.

Option 2
Have a type searching function to automatically determine the type and assign it. This could be a simple helper function with a few conditionals, each with one of the is_* variable functions.
You would want to call the function as a parameter of bindValue().
Pros

This would scale quite well.
It's easy to alter outputs and fine-tune.
You won't have to add the type every time you add a new key/value pair.
Can even check for things such as objects and handle those properly.

Cons

More business code and less model/data code.

I would agree that the SQLParameter is overboard. If anything, maybe one of my solutions will inspire your own.


A good tip is to layout in columns and not rows, similar to a newspaper. That is, divide the page into columns and stack the contents as rows, similar to Pinterest. So, in your site, that makes the iPhone 1 column, and the rest in another column. Now this simplifies things.

Stacking the rest as rows controls their bounds and acts as groupings. That way, if one of these rows were to expand like if the slogan has more text, it does not affect the layout of the next row since the next row clears below it cleanly.

As for pseudocode, it looks something like (Sorry, I really hate typing the <> and {}):

HTML:

div id="wrapper"

  div class="left"
    img src="iphone.png"

  div class="right"

    img class="row" src="logo.png"

    p class="row"
      Picking good food fast

    p class="row"
      Ever think...

    div class="row"
      img src="thumb"
      span
        Yeah...

    ul class="row"
      li
        a
          img src="appstore.png"
      li
        a
          img src="twitter.png"
      li
        a
          img src="facebook.png"

CSS:

#wrapper
  overflow:hidden //just a clearfix
  zoom:1

.row
  display:block  //this makes the element a box
  clear:both     //nothing is at the left and right, and must be above and below

.left
  float:left
  width: something

.right
  overflow:hidden //ensures that the right column does not wrap around left

Off-topic:

Substituting text for images is not good for several reasons:

It's a whole lot heavier than text
SEO (if ever it isn't a myth) isn't that good as they say compared to a text site. So if this is a landing page, better pack it with good description text to summarize the site.
Without properly titled images, screen readers suffer
Resizing the browser either squishes the images or if they scale, the text also shrinks making them unreadable.
Like you mentioned, they are hard to move around

However, a little mix of text and images won't hurt. A general tip is to turn into text whatever can be turned into text. That would be:

Your logo text "dash"
The slogan
Your catch phrases

And don't forget to mind the semantics. Use the proper tags for the job.


Calculating total sales from each member

I won't comment about the fact that this is a static method in what's possibly a static "helper" class and that it would be much prettier in a service class instance... but I just did.
The method is doing way too many things.

Thing one:
// Make a list of all users who are on the team

That's one method. But there's a twist: you not only need all users on the team, but also the teamGoal figure. I'd encapsulate that in its own class:
public class TeamGoalAndUsersResult // todo: rename this class
{
    public IEnumerable<ProPit_User> Users { get; private set; }
    public string Goal { get; private set; }

    public TeamGoalAndUsersResult(string goal, IEnumerable<ProPit_User> users)
    {
        Users = users;
        Goal = goal;
    }
}

And then you can write a method/function that will return that type:
private TeamGoalAndUsersResult GetTeamGoalAndUsers(int teamId)
{
    using (ProsPitEntities db = new ProsPitEntities())
    {
        var goal = string.Empty;
        var team = db.Teams.SingleOrDefault(x => x.teamID == teamId);
        if (team != null)
        {
            goal = Convert.ToString(team.goal);
        }

        var users = db.ProPit_User.Where(x => x.teamID == teamId).ToList();
        return new TeamGoalAndUsersResult(goal, users);
    }
}

Performance Issue:
            var lstorderTotalRep = (from o in db.Orders
                                where o.DateCompleted >= dtStartDate
                                where o.DateCompleted <= dtEndDate
                                where (o.Status == 1 || o.Status == 2)
                                where o.Kiosk != 0
                                where o.SalesRepID == propit_User.SalesRepID
                                orderby o.OrderTotal descending
                                select o.OrderTotal).ToList();

            foreach (var item in lstorderTotalRep)
            {
                //orderTotalRep =+ item;
                orderTotalRep += item;
            }

You're doing all the computation on the client. I'd take a wild guess and say that this is where your bottleneck is. Do you really need to select, sort and materialize all orders just to sum up OrderTotal?
var total = db.Orders.Where(o => o.DateCompleted >= dtStartDate
                              && o.DateCompleted <= dtEndDate
                              && (o.Status == 1 || o.Status == 2)
                              && o.Kiosk != 0
                              && o.SalesRepID == user.SalesRepID)
                     .Sum(o => o.OrderTotal);

orderTotal += total;
dtg.DailyTotal = orderTotal;
dailyTeamGoals.Add(dtg);

The above doesn't sort anything, has the same criterion and performs everything on the server side, without materializing every order in the way. Also I believe if the table has all the fields used in the WHERE, in an index (guts tell me "especially DateCompleted"), that would further help the server-side processing, but that's something you're probably better off finding out with a profiler.


Distributing points uniformly in a unit circle

You can paramterize a circle via a radius and the angle. Therefore, for the  cycle with radius r around (h,w) you can calculate the x and y coordinates with the following equations

x = h + r * sin(theta)
y = w + r *cos(theta)

Therefore your code should look like that
random_device R;
mt19937 G(R());
uniform_real_distribution<double> D(0,360);

for(int i=0; i<N; i++) {
    angle = D(G);
    x = sin(angle);
    y = cos(angle);
}

UPDATE
Toby is right, that this only adds points to the unit circle, rather than the full area of the circle. The solution is rather simple, add a random variable for the radius
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
mt19937 rngAngle(seed);
seed = std::chrono::system_clock::now().time_since_epoch().count();
mt19937 rngRadius(seed);
uniform_real_distribution<double> angleDistribution(0,360);
uniform_real_distribution<double> radiusDistribution(0,1);

for(int i=0; i<N; i++) {
    angle  = angleDistribution(rngAngle);
    radius = radiusDistribution(rngRadius);
    x = radius * sin(angle);
    y = radius * cos(angle);
}

As you have seen, I used some better names too and seeded both random number generators independently with the current time.


The first thing that stands out to me is that you've created an entirely new class that exists purely to have this class method.  This doesn't make a whole lot of sense.  At a minimum, this method could just exist on its own, outside of a class, but I'll do you one better: let's write it as an extension to UIDevice, that's where it makes the most sense, and there are already other similar properties on UIDevice...

extension UIDevice {
    public var SSID: String {
        get {
            // your code
        }
    }
}

Now, getting the SSID will be similar to getting the device name, or system version, or other useful things about the device you might need to know:

let ssid = UIDevice.currentDevice().SSID

Now then, on to the actual meat of your code...

For starters, I don't know much about getting SSIDs.  Is it at all possible that you wouldn't be able to fetch the SSID?  What is the likelihood of actually returning an empty string here?  Importantly, I think returning an empty string isn't actually the right thing to do, no matter how likely it is.

Instead, our return type should be a string optional: String? and we should return nil when something fails.

That way, it's easier on the end user to be certain this returned a valid value:

if let ssid = UIDevice.currentDevice().SSID {
    // do stuff
} else {
    // error fetching ssid
}

This seems easier than the alternative:

let ssid = UIDevice.currentDevice().SSID
if countElements(ssid) > 0 {
    // do stuff
} else {
    // error fetching ssid
}

So, with that out of the way, the only problem I have here is all of this unnecessary nesting and unnecessary variables:

public var SSID: String? {
    get {
        if let interfaces = CNCopySupportedInterfaces() {
            let interfacesArray = interfaces.takeRetainedValue() as [String]
            if let unsafeInterfaceData = CNCopyCurrentNetworkInfo(interfacesArray.firstObject) {
                let interfaceData = unsafeInterfaceData.takeRetainedValue() as Dictionary
                return interfaceData["SSID"]
            }
        }
        return nil
    }
}

Ultimately, there's no reason here to have the three layers of else blocks that all actually do nothing.  In your code you initialize currentSSID to an empty string, and then only change it to anything else if you can get the SSID.  Your three else blocks change currentSSID from an empty string to an empty string, so just omit them completely.


Stylistically, the for loop is more readable.  As a general rule, if you start the loop at 1, then I would prefer the termination condition to use <=; if you start counting from 0, then < would be better.

The design of this function is conceptually flawed.  It will return an unused filename, but presumably you will eventually want to create a file with the name.  However, it is possible that someone else will have created a file with the same name, creating a conflict.  This possible race condition means that you can never be certain that the filename returned by this function is actually unused.

The way to make that guarantee is to actually create the file, such that you effectively grab a reservation on that name.  You can do that by calling File.Open(path, FileMode.CreateNew).  The caller would have to delete the file if it doesn't want it.

private static string CreateNextAvailableFile(string fileNamePrefix)
{
    string name;
    for (int i = 1; i <= 99; ++i)
    {
        try
        {
            FileStream fs = File.Open(name = $"{fileNamePrefix}_{i}.png", FileMode.CreateNew);
            fs.Close();
            return name;
        }
        catch (IOException e)
        {
            // Did File.Open() fail due to name collision or another
            // reason? Unfortunately, no specific "FileAlreadyExists"
            // exception exists.  This is a heuristic, and can be
            // fooled by a race condition where the file was deleted
            // just now by someone else.
            if (!File.Exists(name)) throw;
        }
    }

    throw new ApplicationException("Unable to get free filename");
}

As the comment notes, .NET unfortunately has no way to tell whether the IOException was due to a filename collision or something else.  The code above is therefore also vulnerable to a race condition, but it's better than your race condition, because:

This race condition is only triggered when there is an underlying I/O problem (such as insufficient permissions to create a file, or a read-only filesystem), and the file in question is deleted during the split-second between the File.Open() call and the exception handler.
This code fails in a safer way: if the race condition is triggered, it will throw an IOException.  (Arguably, such an IOException would happen anyway, later on.)  However, it's harder to tell what might be the consequences of your race condition: it might fail to detect a collision, and lead to data being overwritten.


JavaScript dragon slayer game (Codecademy)

Added benefit of function

The function does not seem to have any added benefit right now. For example, running the function twice will not print two "fights". This is mainly because you use global variables. The function is useful if this was a class, where you can set and reset the health of entities. In this case I would just pass them as parameters.

Performance

Performance is about the speed at which the code executes. I do not see flaws which should hamper execution speed too much.

DRY

Your code can be optimized by noticing that the if and the else-statement are nearly identical. You can optimize it by extracting that code and making that it's own function.

Now identify that the log-lines with hp for each entity are duplicated 3 times, twice to tell if we won or not. We can do better. Let's just do it once, and break out of the loop with break when we detect a final conclusion.

The function now does not much useful. We can just put those 2 lines in the first function itself.

For more information, see Wikipedia

Weird damage calculation

totalDamage += damageThisRound;
console.log("You did " + totalDamage + " damage!");
console.log(" ");
dragonHp -= totalDamage;

What is this supposed to do? You reset totalDamage every time, except in a winning/losing condition in which case this code is never executed again.

Variable hoisting

Javascript has a feature called variable hoisting. All variables defined in a context are moved to the top of that context before any other code is executed in that context. I recommend to move all declarations to the top of the context to better match what the code does.

Improvement

function slayDragon( playerHp, dragonHp ) {
  var playerTurn;
  var damageThisTurn;

  while(true) {
    console.log("Player HP: " + Math.max(playerHp, 0));
    console.log("Dragon HP: " + Math.max(dragonHp, 0));

    //End conditions
    if(playerHp <= 0) {
      console.log("YOU ARE DEAD!");
      break;
    } else if(dragonHp <= 0) {
      console.log("YOU WIN!");
      break;
    }

    //Who gets to swing?
    playerTurn = Math.floor(Math.random() * 2);
    damageThisTurn = Math.floor(Math.random() * 50 + 1);

    if( playerTurn ) {
      console.log("You do " + damageThisTurn + " damage.");
      dragonHp -= damageThisTurn;
    } else {
      console.log("Dragon does " + damageThisTurn + " damage.");
      playerHp -= damageThisTurn;
    }

    //Spacing
    console.log("");
  }
}

slayDragon(100, 100);


Or you could do it in two steps, like you do it now. First calculate for each denomination and then sum:

int balance = Account.Select(denom => denom.Currency * denom.BillCount).Sum();


Memoization-based puzzle solution - sums in a triangle

General Comments.
I hate your use of global variables.
int rownum;
int noOfCalls = 0;
vector2D a;
vector2D cache; // The cache to implement memoization

I suppose it is an attempt at better performance.
The test for j here is redundant:
if (cache[i][j] != 0 && ( i < 50) && ( j < 50))

If i is smaller than 50 then j can not be greater than 50. If i is greater than 50 then the test will fail and there is no need to test what the value of j is.
Bugs
    for ( int i = 0 ; i < rownum ; i++) {
        a.push_back(vector1D(rownum,0));//initialize memory
    }

As you never clear a the size increases for every puzzle.
This can become quite expensive as a will continuously keep breaking its buffer and have to be re-allocated (copying all those internal arrays).
Speed
If you are solely going for speed then operator>> is about half the speed of scanf as it (operator>>) takes into account a lot of local stuff that is not done with scanf.
Your recursive algorithm is computing some spots multiple times.
// Your Triangle
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

// Number of times each spot is hit with recursion
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

As you can see some of the spots in the center bottom of the triangle are being hit many many times by recursion when you only want to hit each location once. Thus an iterative solution is probably better.
You are using a 2D array to represent the triangle which requires two de-references (which can be inefficient (but without measuring I am not convinced this is a major issue)). Rather than do that use a 1-D array given the number of rows n you can quickly compute the number of elements in the triangle as n*(n+1)/2 and thus re-size the array in one statement. Element access for a child of m is m+row(m)+0 and m+row(m)+1 (note the calculation of row(m) does not need to be done each time you can keep track of this as you increment m).


Creating default object from empty value in PHP?

Yes, use arrays.

$car = [
   'general' => [
        'interior' => [
            'seats' => 'destroyed'
        ]
    ]
];

$exteriorProperties = [
    'hood' => 'shiny',
    'windows' => 'dirty'
];

foreach($exteriorProperties as $key => $prop){
    $car['other']['exterior'][$key] = $prop;
}
$car = (object) $car;

Anyway, the object conversion will only convert the outermost array. The nested arrays are still arrays.

\is_array($car->general); // true

Why you need it to be shapeless objects anyway? Either define classes for those objects or treat them as arrays is the simple answer.

Btw $car->{'other'} is really weird way of writing $car->other...


Place Ajax request on completion of Ajax Request

From your code it seems like that you are binding a click event on $(".icon") when the ajax completes.

However, you are not making another call after completion of first, but instead making a call on $(".icon").

if you dont want to put ajax call here then you can bind icon with on function with parent selector like below:

$( "#parentDiv " ).on( "click", ".icon", function() {
   //make ajax call
});

more info on this here

you can get help for this from
You should improve your code's clarity to reflect its purpose.


mergeSort([2, 1, 5]) -> [1, 1, 2, 5] ?

You have a bug:

> mergeSort([2, 1, 5]);
[1, 1, 2, 5]

> mergeSort([2, 1, 5, 1, 9]);
[1, 1, 1, 1, 2, 5, 5, 9]

The problem is here:

sort(mergeSort(array.slice(0, Math.ceil(array.length/2))),
            mergeSort(array.slice(Math.floor(array.length/2, array.length))), []);

For example for the array [1, 2, 3],
the first slice will be [1, 2] and the second will be [2, 3],
so 2 gets duplicated.
The more ranges you have with odd length,
the more duplicates will creep in.

I'm also wondering what was the intention of this:

Math.floor(array.length/2, array.length)
                           ^^^^^^^^^^^^  typo?

It seems that changing the slices to this will fix it:

array.slice(0, Math.ceil(array.length / 2)))
array.slice(Math.ceil(array.length / 2), array.length))

Naming

The sort method doesn't "sort".
It merges.
As such, I'd rename it to merge.

Beauty

  i think it's really bad written but i can't figure out a way to "beautify" the code without using a loop

I think it's fine.
This is clear, easy to read, not really ugly.
But I'd use spaces more generously around parentheses, like this:

function merge(left, right, array){
    if (left.length == 0 && right.length == 0) {
        return array;
    } else if (left.length == 0) {
        return array.concat(right);
    } else if (right.length == 0) {
        return array.concat(left);
    } else if (left[0] < right[0]) {
        array.push(left.shift());
    } else {
        array.push(right.shift());
    }
    return merge(left, right, array);
}


Given a pivot x, and a list lst, partition the list into three parts

In your first solution you are traversing the list 3 times, whereas in the second solution only once. Given the functional-tag, I’d say you’re after the reduce function:

const flatten = (acc, x) => acc.concat(x)

const pivotPartition = (pivot, ary) => {
  const toOrdered = (triplet, n) => {
    let [less, equal, greater] = triplet

    switch(true) {
      case n < pivot: less.push(n); break
      case n > pivot: greater.push(n); break
      default: equal.push(n)
    }

    return triplet
  }

  return ary.reduce(toOrdered, [[], [], []]).reduce(flatten)
}

If you want to sort the subarrays as well, then the whole thing is just a ary.sort((a, b) => a - b), although as it is mutating the list, it isn’t a functional solution.


There's a lot to improve about your code, and I'll start from the top. I'll also rewrite some of the logic you had there because IMO it's a bit clumsy and hard to understand.

Imports
Don't use urllib and requests at the same time. Use either one or another. They serve the same purpose.
from bs4 import BeautifulSoup
import os
import random
import requests

As you can see, I've alphabetically ordered them so that it becomes easier to locate each of them.

Constants
You have one url which might be moved at the top of your program. That way, you'll allow your users to change it without searching through all the code.
Moving on, I realised that you didn't give the user a chance to save the pictures wherever he wants. Let's add another constant, say IMAGE_LOCATION.
URL = 'https://pixabay.com'
IMAGE_LOCATION = '/home/images/'

Functions
You can split your code into separate functions so that each of them can serve its own purpose. Read more about Single Responsability Principle:
def get_html_source():
    """Docstring here."""
    html_source = requests.get(URL).text
    return BeautifulSoup(html_source, 'html.parser')

The above function will return a BeautifulSoup object which contains the html source code of the desired URL.
We can now build another function which will generate a path containing a random name for each picture we're downloading:
def image_name():
    """Docstring here."""
    return '{}.jpg'.format(os.path.join(IMAGE_LOCATION, str(random.randrange(1, 100000))))

I've also increased the maximum number just in case there's a huge number of files.
Another helper function would be one that checks if a src URL is a valid one or not. I've modified a bit your condition and made it more strict:
def validate(image_url):
    """Docstring here."""
    return image_url.endswith('.jpg') and image_url.startswith('http')

The above, verifies if the url starts with http (implicitly https will pass) and also if it ends in .jpg.
Only now, we can finally create the download_images function, and wrap our logic into it:
def download_images(soup):
    """Docstring here."""
    for link in soup.find_all('img'):
        image_url = link.get('src')
        if validate(image_url):
            image = requests.get(image_url)
            if image.status_code == 200:
                with open(image_name(), 'wb') as f:
                    f.write(image.content)

As you can see, I've removed most of the logic you had, and simply did the following steps:

Go through all the img tags and save their src attribute (which is an URL
Check the URL if it matches our condition and build our image object
Double check to see if the status code was successful (200) and save the image to our desired location.

Next, wrapping all our code within a main function is as simple as:
def main():
    """Docstring here."""
    soup = get_html_source()
    download_images(soup)

All the code
from bs4 import BeautifulSoup
import os
import random
import requests

URL = 'https://pixabay.com'
IMAGE_LOCATION = '/home/images/'

def get_html_source():
    """Docstring here."""
    html_source = requests.get(URL).text
    return BeautifulSoup(html_source, 'html.parser')

def image_name():
    """Docstring here."""
    return '{}.jpg'.format(os.path.join(IMAGE_LOCATION, str(random.randrange(1, 100000))))

def validate(image_url):
    """Docstring here."""
    return image_url.endswith('.jpg') and image_url.startswith('http')

def download_images(soup):
    """Docstring here."""
    for link in soup.findAll('img'):
        image_url = link.get('src')
        if validate(image_url):
            image = requests.get(image_url)
            if image.status_code == 200:
                with open(image_name(), 'wb') as f:
                    f.write(image.content)

def main():
    """Docstring here."""
    soup = get_html_source()
    download_images(soup)

if __name__ == '__main__':
    main()

If you don't know what's with if __name__ == '__main__' you can read more about it here
More, note that all the functions have a docstring which contain a placeholder like "Docstring here.". You can replace that placeholder with a summary that describes what each function does.


Subclasses instantiating superclass of class Human

Some opinions:

function Woman(){
    Human.call(this);
}
Woman.prototype = new Human();

Don't use new for prototype (even when it doesn't matter here as long as Human is empty, but the Huma.call(this) suggests otherwise). Check https://stackoverflow.com/q/10898786/1048572

// Woman subClass
function Man(){

Apparently not.

    var _foo = 10;

It's a local-scoped ("private") variable anyway, you don't need to prefix it with an underscore. Notice that it is only accessible from functions declared within the constructor, of which you don't have any.

    return Human.call(this);

No reason to return anything here. It might even be wrong it Human did return an object.

Man.prototype.getInfo = function(method, url){
    […]
}

This doesn't seem to have anything to do with instances of Man, so I wonder why it is a method? But that's probably just the design of your test case.

console.log('man private variable _foo: ' + (man._foo));

Not sure what you did expect, but yes, since _foo has been a variable and not a property of the object so this is undefined.

document.body.onclick = function(){
    […]

…is missing a closing brace.

var randNr = Math.floor((Math.random()*1000)+1);
womans[randNr].talk();

No. That randNr will be in the range 1-1000 (both inclusive), while your array indices are 0-999. With a small chance, this will throw an exception. Remove the +1.

console.log('Random Woman: ' + randNr);

…and add it here if you want that output one-based.

Man.prototype.getInfo();

That confirms what I said above - you don't use an instance for that method. You should hardly ever call methods on the prototype object - man.getInfo() would be better. But if you really intended this to be a static function, you might write Man.getInfo = function() {…}; and then call Man.getInfo();.


I never found a code that was simple and easy to understand yet wasn't any slower

Note the order. Start readable.
Start with What shall this be good for?: (doc)comment your code.

No slower than what? A "well known implementation" for reference and as a base-line would be useful.

Things I liked:

"non-obvious" code blocks are commented
(short-circuit set-up, negative numbers sort)
trying to keep the number of passes low
handling of negative numbers via histogram instead of value manipulation

Dislikes (beyond missing doc comments):

not declaring the size parameter const N
this would at least hint that the memory pointed to by A and Temp may be modified
naming
while I like i for index without further significance, I prefer p for a pointer
What is the significance of Z in Z1…4?
case:
assuming capital case OK for arrays: why N, T, Jump1…4?
naked literals (beyond 0±1)
repetition
starting with types: have a value type, a histogram type
with "the rearrangement blocks", I'd prefer benchmark/machine code comparisons between
zeroing memory with open code - use memset(destination, 0, count)
"empty then" instead of inverting the condition
*(p+e) instead of p[e] (let alone *(e+p)) - without revisiting the standard, I would have denied this was well defined.)
updating a counter using increment/decrement
I think of those operations as next/previous and use += 1(-= 1) for numerical adjustment
not using an explicit variable (histogram handling, mostly)
re. speed: not special-casing "small" arrays

Things I don't want to presume warranted:

bit operations preferred to ldiv_t ldiv()
bit operations using compile time constants over using parameters (would allow factoring out)
"walking memory backwards" as fast as "forwards"


Defining many HTTP request methods in a class using partialmethods

It is certainly possible to do what was outlined that lies outside the class definition within the class definition itself through the usage of locals, and with that the intent of what is to be done can be expressed more clearly with less verbose code and lookup using setattr.

class SeshTester:
    def __init__(self):
        self.s = Session()

    def request(self, method, *args, **kwargs):
        return self.s.request(method, *args, **kwargs)

    for r_method in ['delete', 'get', 'head', 'options']:
        locals()[r_method] = partialmethod(request, r_method, timeout=7)

    for r_method in ['connect', 'put', 'push']:
        locals()[r_method] = partialmethod(request, r_method, timeout=13)

Seeing this working as intended from the shell:

>>> SeshTester().get
functools.partial(<bound method SeshTester.request of <__main__.SeshTester object at 0x7fde00176ef0>>, 'get', timeout=7)
>>> SeshTester().put
functools.partial(<bound method SeshTester.request of <__main__.SeshTester object at 0x7fddf8da0668>>, 'put', timeout=13)

One more thing: the documentation linked above does not actually describe what is implemented, at least for CPython; other implementations may have locals() behave differently within the class scope, however there is now an effort to properly standardize this underspecified behavior to the CPython implementation in PEP-558, such that the above code example will work as intended according to the standard (if the PEP gets ratified into Python 3.7).

However, as mentioned in the question, if the API provides a standardized helper method that provides a specific Session instance, certainly it can provide a subclassed Session instance with the specific features/methods that require overriding be applied where needed.  Consider the following:

class SessionExtras(Session):

    def request(self, method, url, *a, **kw):
        default_timeout = 7
        timeouts = {
            'CONNECT': 13,
            'PUT': 13,
            'PUSH': 13,
        }
        if kw.get('timeout') is None:
            kw['timeout'] = timeouts.get(method, default_timeout)
        return super().request(method, url, *a, **kw)

Perhaps this way the intent of what is to be done is expressed in a much more clear way, and allow the API users to make use of a real Session instance rather than some surrogate.  For this example, the default_timeout and timeouts is defined within the function definition, however they could conceivably be moved to the class or even module level, depending on the intended usage and how it is to be customized for the specific API that is being written.


You've got the right idea! By passing the values in along with the query you're doing what other languages call a "prepare" on the final query to make sure that the values being passed are quoted/escaped properly to avoid issues with injection.


Is this an efficient merge sort implementation with regards to average time complexity in Big-O notation?

Is my below merge sort implementation in O(n log n)?

No, while your merge sort appears to be a good implementation of the in-place merge sort, that sort has a complexity of O(n log2n ). While the complexity may look reasonably scalable, the actual surt is quite slow compared to others. Specifically, it is a much slower sort than the native TimSort used by the Collections API in Java7 and above.

@tintinmj is right to challenge the use of a String input parameter for nthElement. It should be a simple int input parameter.

You should note that you could get to the nthElement faster by moving backwards from the end of the sorted data. If you move forwards you have to scan the entire array. If you move backwards, you only have to go as far as the matching value.

OK, so the input parameters are of the wrong type, the sort is more expensive than anticipated, and the final scan could be faster ... but, the real question I have is why not just scan the data once and be done with it....

private static final int nthLagest(int[] data, int nth) {
    int[] result = new int[nth];
    int rescnt = 0;
    for (int d : data) {
        // read the documentation for binarySearch, and why I do ` - xxx - 1`
        int ip = - Arrays.binarySearch(result, 0, rescnt, d) - 1;
        if (ip >= 0) {

            // this value is not recorded... which may be because it is good,
            // or because it is not better than the nth.
            if (rescnt < result.length) {
                // we don't have nth large numbers yet.
                System.arraycopy(result, ip, result, ip + 1, rescnt - ip);
                rescnt++;
                result[ip] = d;
            } else if (ip > 0) {
                // this value is larger than one of the nth values we already have.
                ip = ip - 1;
                System.arraycopy(result, 1, result, 0, ip);
                result[ip] = d;
            }
        }
    }
    if (rescnt < result.length) {
        throw new IllegalStateException("There is no " + nth + " largest value in " + Arrays.toString(data));
    }
    return  result[0];
}

The above function takes the data, and scans through it just once. As it goes, it keeps track of the highest 'n' numbers, where 'n' is the nth largest number you want to get.

The overall complexity for this function is something like O(n log m) where n is the number of elements in the input data, and m is the input value nth (if you want to get the third-largest value, then m = 3).