Time limit exceeded for SPOJ problem "Prime Generator"

Disclaimer: I haven't tried the challenge myself so it will be pretty generic advices.

A bit of style

Python has a style guide called PEP 8. You'll find various tools to check that your code complies to it such as pep8, various tools to fix your code (such as autopep8). I also highly recommand testing other tools to check your code such as pylint, pychecker, pyflakes...

Problems in your code are mostly related to whitespace but you might want to get the habit of doing it right.

Also, as far as style is concerned : the x variable does not seem to be very useful (its name does not convey much meaning and the value does not change) ; the variable test is not used as such, the convention is to name throw-away values _.

A bit of scaffolding

A piece of code like the one you've submitted is quite hard to test as it is. Indeed, the only way to play with it is with input/output. This makes it quite hard to write automatic tests to ensure you do not break the algorithm but also to write performance tests to make your optimisations actually are optimisations.

Let's try to separate the concerns to have the actual algorithm on its own and the input/ouput in a different place.

Here's what I have done : the function takes a list of tuple (min, max) and returns a list of list so that each list corresponds to the list of primes. Then it is just a matter of pretty printing to solve the challenge.

I have converted the test in the example and some more to automatic tests :

def algo(input_val):
    sol = []
    for minim, maxim in input_val:
        primes = []
        if minim == 1:
            minim += 1
        for number in xrange(minim, maxim + 1):
            if number == 2:
                primes.append(number)
            for i in xrange(2, number):
                if number % i == 0:
                    break
                elif i == number - 1:
                    primes.append(number)
        sol.append(primes)
    return sol

def tests():
    assert algo([(1, 10), (3, 5)]) == [[2, 3, 5, 7], [3, 5]]
    assert algo([(5, 100)]) == [[5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]]
    assert algo([(5, 100)] * 100) == [[5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]] * 100
    algo([(10000, 50000)])

def main():
    input_val = [map(int, raw_input().split()) for _ in xrange(int(raw_input()))]
    output_val = algo(input_val)
    print(output_val)

if __name__ == '__main__':
    tests()

Better algorithms

At the moment, algo([(10000, 50000)]) is already very slow, there is no way you'll get to the extreme values in a correct time. You'll have to improve algorithms.

Better check for primeness

At the moment, when checking whether n is prime, you consider all potential divisors up to n. It is not worth the pain at least one divisor would be smaller or equal to the square root of n.

Also, it might be worth extracting the corresponding logic in a function on its own for clarity purposes (it took me a while to understand that minim += 1 was a premature optimisation).

Once it is done, you can realise that you can do even better than this by considering only odd numbers if the number is not divisible by 2 but I won't care about this yet.

The code is already much faster and looks like :

def is_prime(n):
    """Checks if a number is prime."""
    if n < 2:
        return False
    return all(n % i for i in range(2, int(math.sqrt(n)) + 1))

def algo(input_val):
    sol = []
    for minim, maxim in input_val:
        primes = []
        for number in xrange(minim, maxim + 1):
            if is_prime(number):
                primes.append(number)
        sol.append(primes)
    return sol

You can make it fancier by using list comprehension :

def algo(input_val):
    sol = []
    for minim, maxim in input_val:
        sol.append([n for n in xrange(minim, maxim + 1) if is_prime(n)])
    return sol

or even :

def algo(input_val):
    return [[n for n in xrange(minim, maxim + 1) if is_prime(n)]
            for minim, maxim in input_val
            ]

You can already handle much bigger values.

More tricks to handle bigger inputs

A trick to perform things quicker is to precompute values to be able to reuse them quickly. Such an algorithm for prime number is called the Sieve of Erathosthenes. You won't be able to compute it for the maximum values (n <= 1000000000) but it could be worth storing a list of primes up to sqrt(max) where max is the maximum max value in the input. If you do so, you'll perform the sieve for values up to maximum 31622 which is realistic. Then instead of checking all divisors, you can check only prime values (as primes gets rarer and rarer, I expect this to make the code faster).

Another trick might be to try to handle overlapping test cases by not performing the same actions many times.


import*:

Please avoid importing all modules at all costs. Import each module you use separately

Regex ಠ_ಠ

Regex is evil, the worst. seriously. stop it. right now. kill python.exe right now and change it.

You use beautifulsoup, a dom parsing library, literally a few lines later, but you choose to use regex.

You sir, are evil.

I would suggest looking further at beautifulsoup, or taking a look at Scrapy, a scraping library for Python that makes use of generators to scrape large element sets (and even has cloud support!)

Lisp

Your code reads like lisp.

    ))
  )) )

Seriously, you need to format this better.

Try using Python's style guide, PEP8. when running your code through the online analyser, it threw 20 errors immediately.

When coding good Python, PEP8 should be your goto style document.

Looping

You shouldn't be looping like this:

print {key: int(value) for key, value in

If you want to reduce the code indentation level, then you should use separate variables to store each step in the process, or just simply use a standard loop.

String formatting

Instead of using % (myString), you should use string.format, as it's an improvement for these reasons:

less independant of parameter order
More readable

"My name is {name}, and I work for {work_name} as a {job_name}".format(name="Batman", work_name="Gotham City", job_name="Crimestopper")


You can use the connect function, which returns the default connection.

Just add mongoose.connect('mongodb://username:password@host:port/database'); whenever you need it.

See http://mongoosejs.com/docs/connections.html


Based on these two lines…

xpost_create("bgr",
        XPOST_OUTPUT_BUFFEROUT,
        &buffer_type_object,
        XPOST_SHOWPAGE_RETURN,
        1);
xpost_run(XPOST_INPUT_STRING, prog);

I am puzzled by the interaction between xpost_create() and xpost_run().  Is it possible to create and use multiple xpost contexts at once?  If so, shouldn't xpost_create() return some kind of handle that would be passed as a parameter to xpost_run()?  Or, if not, then why should I need to call xpost_create() and xpost_destroy() at all?

I would expect the library to behave more like a printer, in that it would produce an image for every showpage command.  One way to make that work would be to register a callback, which would be called whenever showpage is encountered.  Perhaps it could pass some information about the bounding box as parameters to the callback, since it's unreasonable to have to guess or hard-code that information.

It's odd that the color model is called "bgr", but the pixel values are arranged in the opposite order (red, green, blue) in the output buffer.  I would also consider treating the buffer as an array of

typedef {
    int red;
    int green;
    int blue;
} struct pixel;

… instead of separate red, green, and blue integers.

Your example client doesn't seem to demonstrate any error-handling capability.  What happens, for example, if the PostScript interpreter has a stack underflow?


Evaluating π using Monte Carlo methods - Serial vs OMP

Correctness issues

Correctness merits priority over efficiency. Important to get a correct answer, not a  fast and wrong one.

Poor use of mixing types

long interval, and int i lead to undefined behavior (UB) when interval > INT_MAX.  Use same type.

Small range

long may use 32-bit.  Easy enough to run in less than 1 minute and exceed 231 - limiting how far we can test this code.  Use long long or, use unsigned long long.

Off-by-1

Using / (double) RAND_MAX  may impart a small bias.  Yet given the slow  convergence of the Monte Carlo PI, I doubt any serious miscalculation.

I'd expect the random values to be in the middle of each random range:

[0.5, 1.5, 2.5, ... RAND_MAX - 1.5, RAND_MAX - 0.5, RAND_MAX + 0.5]/(RAND_MAX + 1u)

Code has then distributed differently:

[0.0, 1.0/RAND_MAX, 2.0/RAND_MAX, ... 1.0]

A more significant bias occurs when (int)(double) RAND_MAX != RAND_MAX - select platforms with more precision in RAND_MAX than double.

Note: to convert RAND_MAX plus 1 to double, code can use (RAND_MAX/2 + 1)*2.0.  Works well when RAND_MAX is a Mersenne Number or and odd value.  This avoids losing precision that (double)RAND_MAX + 1.0 may incur.

Efficiency

pow() vs x*x

A weak compiler may use a laborious function call seeing pow(x,2) and not the certainly more efficient x*x replacement.  Of course the right answer is to use a smart  compiler.  Still, profiling a direct coding of x*x may prove worth-wild.

fp vs. integer

I'd even consider an integer only approach.  Something like the below.

// int2x twice as wide as int
int2x limit = (int2x) RAND_MAX * RAND_MAX;
...
  int2x x = rand();
  int2x y = rand();
  if (x*x + y*y <= limit) circle++;

double vs. long double

Seriously doubt any calculation run within a day will benefit using the higher precision long double.

// return (long double) circle / interval * 4.0;
return circle / interval * 4.0;

No comment on OP's major goal: Serial vs OMP - sorry.


// Not following Swift naming conventions, should be bytesPerPixel
let BytesPerPixel = 4

// Better to make function throwable and throw specific error.
guard let srcProv = srcImg.dataProvider else { fatalError("dataProvider is nil") }
guard let srcProvData = srcProv.data else { fatalError("dataProvider.data is nil") }

For unwrap of srcImg.colorSpace! is not good solution, I would recommend to use guard ... else and throw an exception if value is nil.

Overall: why you are using abbreviations and shortcuts for every variable/constant name? It is much harder to read such code


Sorting an empty array is perfectly valid.

if (c.size() == 0) {
    throw std::out_of_range("no size");
}

The result id an empty array. An exception is not the correct way to go.

OK optimize. An array of size 0 or 1 is already sorted.

if (c.size() == 1) {  // I would make this c.size() <= 1 (as I would remove the exception)
    return;
}

Special casing the std::end(c) just looks wrong.

   while (i+1 != std::end(c) && *(++i) < p) {

I would say that if i+1 == high would be a better test. Also adding the ++ and * operators into the expression makes it really hard to read. I would go with:

    while ((i < high) && (*i < p)) { ++i;}

The decrementing the j pointer should look exactly the same as the increment.

This is not tested (so may have bugs).
But this is how I would write partition.

// Note: this function require std::distance(low, high) >= 3
// Note: it is called from sort when std::distance(low, high) > 15
template<typename I>
std::pair<I,I> partition(I low, I high) {
    --high;
    I   pivot   = high;

    I   highBot = low;
    I   lowTop  = high;
    --lowTop;
    while (highBot < lowTop) {
        while ((highBot < high)  && (*highBot <= *pivot))   { ++highBot;}
        while ((lowTop >= low)   && (*pivot < *lowTop))     { --lowTop;}
        if (highBot < lowTop) {
            std::swap(*highBot, *lowTop);
        }
    }
    // At this point highBot and lowTop have just passed each other.
    // Thus highBot points to the first element greater than *pivot
    // and lowTop points to the last element smaller or equal to *pivot
    swap(*highBot, *pivot);

    // Now: highBot points to the pivot value and the value that was
    // at highBot is in the top end of the high range.

    // We want to to remove pivot value from the range of elements to be sorted.
    // so we want to sort the two ranges likes this:
    //
    //      [low..lowTop+1)
    //      highBot                 The pivot point removed from further sorting.
    //                              Note: lopTop+1 == highBot
    //      [highBot+1..high)
    //

    // Small optimization
    // If the value at lowTop is also equal to the pivot value
    // Then we can remove it from further sorting.
    for(; (lowTop >= low) && (*p == *lowTop); --lowTop) {}

    return std::make_pair(lowTop+1, highBot+1);
}

Usage:

std::pair<I,I> part = partition(low, high);
sort(c, low, part.first);
sort(c, part.second, high);


It seems fine for me.

Some small changes:

I'd change the action to

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">

Using PHP_SELF in the action field of a form
I'd consider storing escaped data in the database instead of escaping them on every page requests for performance reasons if the page has lots of visitors.
"../post.sqlite" should be a constant.
I'd reorganize the code a little bit to use only one SQLite3 instance:

define("DB_FILE", "../post.sqlite");

$dbExists = file_exists(DB_FILE);
$db = new SQLite3(DB_FILE);
if (!$dbExists) {
   $db->exec("CREATE TABLE posts( id INTEGER PRIMARY KEY, post TEXT )");
}

if (isset($_POST['data'])) {
    if( isset($_POST['password']) && $_POST['password'] === "correct horse battery staple" ){
        $statement = $db->prepare("INSERT INTO posts( id, post ) VALUES ( NULL, ? )");
        $statement->bindValue(1, $_POST['data'], SQLITE3_TEXT);
        $statement->execute();
    }
}

function posts($db) {
    $query = $db->query("SELECT post FROM posts ORDER BY id DESC");

    while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
        print( "
" );
        print( htmlentities( $row['post'] ) );
        print( "

" );
    }
}

?>
[...]

            <?php posts($db); ?>
[...]

<?php
    $db->close();
?>

It may be worth creating the table with IF NOT EXISTS in every execution instead of the file_exists check for simplicity: Creating an SQLite table only if it doesn't already exist


How can I efficiently manipulate digits in a string without using RegEx in Java?

TL;DR
private String increment(String input){
    char[] chars = input.toCharArray();

    boolean stopLoop = false;
    for(int i = chars.length - 1; i >= 0; i--){
        char character = chars[i];
        switch (character) {
            case '0', '1', '2', '3', '4', '5', '6', '7', '8' -> {
                chars[i] = (char) (character + 1);
                stopLoop = true;
            }
            case '9' -> chars[i] = '0';
            default -> {
                if(i + 1 < chars.length && chars[i + 1] == '0')
                    stopLoop = true;
            }
        }

        if(stopLoop)
            break;
    }

    return  new String(chars);
}

The quizzes of the coding interviews have some goals:

To check if the knowledge that the candidate claims is true.
To filter candidates when you have too many applications.
To know if you think beyond the obvious solution.
To know how deep you know about a language, or a version of it.
To check if you have some knowledge of data structures, algorithms
and time / space complexity of algorigthms.

Here the obvious solution is to work with Strings. Knowing that String in Java are immutable, you have to do all the stuff splitting and concatenating Strings. My proposal is to convert the String into a char array, work with it, and convert it back to an array.
The cost in time of reading and writting into an array is constant, while making all the work with strings has a higher time cost. In an interview is not so important, but for a backend position it is.
Is the char array the best thing ever? It is not, specially in this example. The good of it, is that you can use it like an integer of one byte space in memory. The bad, is because that behaviour, the editor wont tell you that you are writting 0 instead of '0'. 0 is the value of the NUL Ascii character. The Ascii value of '0' is 48. Well, this problem is designed to know if you write too error prone code.
When you have the char array, you traverse it backwards. To traverse backwards is more error prone than to traverse forwards (IndexOutOfBoundExceptions). So, it is another way to check how many errors do you write without the help of your editor, or without compiling several times.
Because you can use char as a value, it is perfect to use it into a switch statement. The first nine cases (from '0' to '8' character) share the same behaviour and code: Increment to next character and end the edition of the characters.
The case of character '9' requires to replace this character with '0' and check the previous character in the array.
The default case is the trickiest. It ignores the characters that aren't numbers if they appear before the characters that are numbers (remember, it is backwards traversing). When one number appears there are two options: the first option is one of the first nine cases, the other option is the case of a '9' converted into a '0'. So, if you find a non number character followed of a '0' the algorithm finishes.
The last step is to convert the char array back into a String, what you can do easily calling one of the String constructors.
You won't face this kind of problem in real life. You will use regular expresions. It is just to check you knowledge, in this case about Java. If you find a problem which solution is too complicate, try a less obvious one.
I hope it helped you.


Effective usage of multiple joins in Eloquent dependent on variable

I don't see a way to do it with eager loads. I wonder if you could reduce it to getBy($k, $v) using distinct though?

class Movie extends Eloquent
{

    function writers()
    {
        return $this->belongsToMany('Writer');
    }

    function actors()
    {
        return $this->belongsToMany('Actor');
    }

    /**
     * Get a list of Movies with the matching the key-value.
     *
     * @param string $k Key (movie attribute) name
     * @param string $v Value of the movie attribute
     *
     * @return \Illuminate\Database\Query\Builder
     */
    function getBy($k, $v) {
        return Movie::join('movie_writers as mw', 'mw.movie_id', '=', 'movie.id')
            ->join('writers as w', 'w.id', '=', 'mw.writer_id')
            ->join('movie_actors as ma', 'ma.movie_id', '=', 'movie.id')
            ->join('actors as a', 'a.id', '=', 'mw.actor_id')
            ->where('movie.status','=','active')
            ->select('movie.id', 'movie.name')
            ->where($k, 'like', "%$v%")
            ->distinct();
    }
}

With this in place, getBy will return a Query Builder object that you can filter by restricted and limit.

$movie = new Movie();
$movies = $movie->getBy('writers.name', 'Matthew Weiner')
                ->whereNotIn('movie.id', $this->restricted())
                ->take($limit)
                ->skip($offset)
                ->get();

Then you can take the a step further by pulling this method out into a MovieRepository that implements MovieRepositoryInterface. Check out this Laracasts episode for more on that. It could have a MovieRepository->restrictedBy(Builder $builder, $restrictedList) that also returns a Builder object.


I think your code could use some restructuring:

The name Sherlock_and_The_Beast is more applicable as a module name instead of a function name. Now, even though I said 'more applicable', it does not mean I would suggest naming your Python script this. I would instead call it sherlock.py.*
Your function should be named something like generate_decent_number. This gives a better description of what it actually does.
I would have your function take a single integer instead of a list and then return the decent number. Doing so, removes the need for a flag variable.
Use xrange instead of range.

There are also a few style notes to point out:

Use descriptive variable names. Even though i (and to some extent j) have been conventionalized as indexing names, I prefer to be more descriptive. i should be item and j should be num.
Use whitespace appropriately. Put single spaces around assignment or conditional operators:

foo = 'bar'
if foo == 'bar'

I prefer to use not when I can. Because 0 evaluates to False in conditional statements, you can use:

elif not item % 5:

instead of:

elif item%5 == 0:

This is mostly a personal preference. Some people abhor checking for negative conditions.

Past these notes above, your code is simple and straightforward which are both Pythonic conventions.

Here is my version:

def get_decent_number(num_digits):
    if num_digits < 3:
        return -1

    three = str(3)
    five = str(5)
    if not num_digits % 3:
        return five*num_digits
    elif num_digits == 5:
        return three*num_digits

    for num in xrange(num_digits/3, -1, -1):
        diff = num_digits - 3*num
        if not diff % 5:
            return five*3*num + three*diff

    return -1


Reading a CSV file containing a dataset of 8×8 images

Outline

Data and Main aren't exactly helpful class names.  I suggest ImageMatrix and ImageMatrixDB.

In some sense, your code is incomplete, because it just prints the data that it read.  To make this code useful, you would have to offer a way to retrieve the data — and not just by directly accessing dataSetList and dataArray, which should have been private.  I suggest the an outline like this:

ImageMatrix.java

public class ImageMatrix {
    public ImageMatrix(int[] data, int classCode) {
        assert data.length == 64;
        …
    }

    public int[] getData() {
        …
    }

    public int getClassCode() {
        …
    }
}

ImageMatrixDB.java

public class ImageMatrixDB implements Iterable<ImageMatrix> {
    private List<ImageMatrix> list = new ArrayList<>;

    public static ImageMatrixDB load(File f) throws IOException {
        …
    }

    public Iterator<ImageMatrix> iterator() {
        return this.list.iterator();
    }
}

Why are you storing the same data twice, in both dataSetList and dataArray?  You should drop the dataArray, which relies on the magic number 2810.

The file parameter should be a File rather than a String, so as not to give the impression that you it accepts the contents of the file rather than the name of the file.

The parsing routine needs a way to report failure to its caller.  No, printing an error message doesn't count, as the caller would still proceed obliviously.

Implementation

Why are you using a Scanner?  The BufferedReader already has a readLine() method that does what you want.  Note that you fail to close the FileReader, BufferedReader, and the Scanner.

In the Data object, the dataSet array has 65 elements: the 64 data points and the class code.  The class code has no business being part of that array.

public static ImageMatrixDB load(File f) throws IOException {
    ImageMatrixDB result = new ImageMatrixDB();
    try (FileReader fr = new FileReader(f);
         BufferedReader br = new BufferedReader(fr)) {
        for (String line; null != (line = br.readLine()); ) {
            int lastComma = line.lastIndexOf(',');
            int classCode = Integer.parseInt(line.substring(1 + lastComma));
            int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
                               .mapToInt(Integer::parseInt)
                               .toArray();
            result.list.add(new ImageMatrix(data, classCode));
        }
    }
    return result;
}


Arduino controller to control the backlighting of a gear selector

I see some things that may help you improve your code.

The Arduino language isn't C

The language used for the Arduino isn't quite C and isn't quite C++, so if your goal is "to learn C," you might want to be careful about the differences.  Specifically, the Arduino's use of setup and loop is unique to it.  Also, all of the "built-in" things such as digitalWrite and Serial are non-standard.  You can still learn useful things by learning to program the Arduino, but it's important to remain aware of the differences.

Know the differences between C++ and C

As mentioned above, the Arduino language isn't quite C or C++, but in most ways, it's closer to C++ than C.  One such difference that affects this code is the use of the struct interval.  In C++ the name of a struct automatically defines a type.  In C, it does not.  So the state in plain C would need to be written like this:

struct state
{
    char name;
    int led;
    struct interval gauss1;
    struct interval gauss2;
};

Alternatively, one could use a typedef in the declaration of the interval structure like this:

typedef struct interval_s
{
    int lower;
    int upper;
} interval;

Eliminate global variables where practical

Having routines dependent on global variables makes it that much more difficult to understand the logic and introduces many opportunities for error.  Eliminating global variables where practical is always a good idea, whether programming for desktop machines or for embedded systems.  For global variables such as prev_gauss1 and prev_gauss2, consider wrapping them in objects to make it easier to see that they're related.  Here again, this is a difference in the Arduino language where it is common to have global variables and plain C where it is rare.

Understand the fundamental types

The analogRead() call returns an int (which is 2 bytes on the Arduino), but the converted value of gauss1 and gauss2 is a long which is 4 bytes long on the Arduino.  However, all of the numbers in the table are small enough to fit into an int which suggests that you probably don't really need a long there.

Minimize runtime conversions

It's not critical here, because normal drivers don't expect microsecond shifting, but in general, it's good to minimize the work that an embedded system must do at runtime.  This tends to make the program more efficient and more responsive, as well as usually resulting in smaller code.  In this case, the raw readings are taken from the sensors, converted using a simple linear equation and then compared to fixed values in the table.  Instead, the table could store the corresponding raw values and the comparison could be made without conversion.

Make use of defined constants

The numLED constant is defined, correctly, but their connection to the array of states is not explicit.  I'd suggest changing the declaration from this:

state shift_condition[] = {

To this:

state shift_condition[numLED] = {

Reconsider naming

The names gauss1 and gauss2 are not terrible, but it might be worth considering what the values really mean.  Because they're actually sensor data, it might be better to name them for what they represent rather than the units.

Set states explicitly

The only time the U_led is written, it's set HIGH if no states are matched.  If it ever gets to that point, there's no recovery even if it gets in range of one of the gears.  Further, it's often good in embedded systems to set states explicitly.  So when you set one LED, it's often good to explicitly unset the LEDs that are not supposed to be lit.  The reason for this is that glitches can happen in the real world.  For example, an energetic gamma particle can flip a bit in RAM and it's useful to have a recovery for such events.


Like system with MySQL on multiple types of pages

This design violates first normal form, which is a concept that states that each data field should contain an atomic value (using type and ID together makes this a composite value).

This makes certain types of queries more difficult, and you'll use more database space and suffer query performance.

Store the type in one column, and the ID in another. If you have many tables, you might consider breaking it out so each module type has a corresponding "likes" table (e.g. news and news_likes. This uses significantly less space and makes maintenance easier, but makes some queries harder (such as "show me all my likes").

Using a single-table notation is acceptable, but by breaking the type and ID out, you can use an enum and an int instead of a var char, which will improve query speed on full-table scans, and use less space on disk.


Unit tests code for a Java class that that checks whether an array is sorted

I don't see anything wrong with the way you are testing.

You may want to include negative numbers in your test cases.

I prefer to have test cases broken up. It's easier to track down failing tests:

@Test
public void testIsSortedSingleNode()
{
    int[] C = { 32 };
    assertEquals(true, SortedOrNot.isSorted(C));
}

Even in tests you should follow naming standards. Names such as A, B C are not very descriptive. Also they should start with a lower-case letter. result would be a better name. You use the same variable throughout.

Use assertTrue and assertFalse instead of assertEquals(true/false, x).

IMO arrayLength would be a better name then n. Or you could use arr.length.


Copy certain lines from one text file to another

It is OK to use File.ReadLines(...) because it actually is shortcut to StreamReader.ReadLine() (Not to be confused with File.ReadAllLines()).

I wonder why you reopen the same file for each line you want to save. I would do something like this:

  byte[] arrayByte = { 0x00 };

  using (var stream = new FileStream(fileName + "_gugggu", FileMode.Create))
  {
    foreach (string line in File.ReadLines(fileName).Where(l => l.Contains(":10")))
    {
      ...

This may be the real bottleneck.

I think

      string partialA = line.Substring(9);
      string partialB = partialA.Remove(partialA.Length - 2);

is the same as:

      string subString = line.Substring(9, line.Length - 11); // 11 = 9 + 2

All  in all it could be changed to :

  byte[] arrayByte = { 0x00 };

  using (var stream = new FileStream(fileName + "_gugggu", FileMode.Create))
  {
    foreach (string line in File.ReadLines(fileName).Where(l => l.Contains(":10")))
    {
      string subString = line.Substring(9, line.Length - 11);
      arrayByte = ToByteArray(subString);
      stream.Write(arrayByte, 0, arrayByte.Length);
    }
  }


Print the Twelve Days of Christmas without loops or conditionals

Recursion is something that is often "unwrapped" to become loops, but the same is true, in the other direction. Almost all loops can be implemented as recursion.

Using your "trick" of throwing an exception to act as a conditional, it would be simple to turn all your code... this code:

public static final String verseText =
    "On the %s day of Christmas,\n" +
    "My true love sent to me\n" +
    "%s";

public static void main(String[] args) {
    //Print the song
    System.out.println(song());
}

public static String song() {
    //The song consists of all verses up to verse 12, but the index starts from 0
    //Print verses 0 to 11
    return versesBelow(11);
}

public static String versesBelow(int verse) {
    //Evil hack that allows me to check whether the input is zero without using a conditional ;)
    try {
        //Divide by verse. If the verse is zero, then an ArithmeticException is thrown.
        //I am not using a conditional here!!!
        int i = 1 / verse;
    }
    catch(ArithmeticException ex) {
        //Stop the recursion
        return verse(verse);
    }
    //else return this verse and all the verses below this one.
    return versesBelow(verse - 1) + verse(verse);
}

public static String verse(int verse) {
    //Format the string with the correct day and verse and add a newline for a blank space after
    return String.format(verseText, days[verse], linesBelow(verse)) + '\n';
}

public static String linesBelow(int line) {
    //Same evil hack
    try {
        int i = 1 / line;
    }
    catch(ArithmeticException ex) {
        //Stop the recursion if line is zero
        return line(line);
    }
    //Else return this line and all the lines below this line
    return line(line) + linesBelow(line - 1);
}

public static String line(int line) {
    //Return this line and a newline
    return lines[line] + '\n';
}

in to just:

public static void main(String[] args) {
    try {
        recurseDown(0);
    } catch (RuntimeException e) {
        // nothing.
    }
}

private static void recurseDown(int i) {
    System.out.println("\nOn the " + days[i] + " day of Christmas\nMy true love sent to me");
    try {
        recurseUp(i);
    } catch (RuntimeException e) {
        // nothing.
    }
    recurseDown(i + 1);
}

private static void recurseUp(int i) {
    System.out.println(lines[i]);
    recurseUp(i - 1);
}

you can see it running here: http://ideone.com/SAte6Z

Written properly, it would be:

public static void main(String[] args) {
    recurseDown(0);
}

private static void recurseDown(int i) {
    if (i == days.length) {
        return;
    }
    System.out.println("\nOn the " + days[i] + " day of Christmas\nMy true love sent to me");
    recurseUp(i);

    recurseDown(i + 1);
}

private static void recurseUp(int i) {
    if (i < 0) {
        return;
    }
    System.out.println(lines[i]);
    recurseUp(i - 1);
}


My attempt at a weighted search in JavaScript

I like it, from a once over:

map, filter, reduce etc. are not the most efficient functions, they make for readable code, not for speedy sorting/searching. See this : http://jsperf.com/arraymap, a simply for loop beats everything else every time, this also goes for filter,reduce etc.
I would change around the first block, there is too much happening horizontally:

return array.map(function (e) {
    return {
        element: e,
        weight: weightedTests.map(function (weightedTest) {
            return weightedTest.test(e) * weightedTest.weight;
        }).reduce(function (previousValue, currentValue) {
            return previousValue + currentValue; }, 0)
     };
 })

The sorting by weight I would do like this:

//sort first by weight if possible
var weightDifference = obj2.weight- obj1.weight;
if (weightDifference) {
  return weightDifference;
}

The last return 0 does not need to be in an else block
Other than that the code runs fine on JsHint, is well commented and easy to follow.


Small nitpicks

AFAICT Resource::mResourceId is unused, and Resource::mResourcePath might not be necessary (in worst case, it could be queried from the ResourceManager).
For better portability, make the type of Texture::data uint8_t, as char might not be 8 bits wide on all platforms.
Inconsistent naming: sometimes it's name, sometimes it's path. Choose one and stick with it!
Also, hopefully all paths follow the same convention (e.g. no backslashes under windows, no superfluous slashes, etc.), otherwise a resource with the same physical location might be loaded for multiple different paths. Maybe introduce a way to make paths compliant to a convention (e.g. a method make_unique_path or similar).

Implementation

If a resource path is already loaded as another resource type, ResourceManager::load returns a dangling (null) reference. Maybe throw an exception instead?

Design

Are there any actual cases where Resource::unload() actually has to do anything (e.g. write the resource back)? Usually resources are read-only, so this member function might not be needed.
I would make it the Resource constructors responsibility to load the resource (and the destructors responsibility to unload it if necessary). This way, there is never an "unloaded/not yet loaded" state of a resource that has to be checked everywhere.
ResourceManager has a communication issue if the same resource is required by 2 or more clients: Who does the cleanup (who gets to call ResourceManager::unload(const std::string&))? If done to early, every other client has a dangling reference. If not done at all, the resource will only be cleaned up when the ResourceManager is destructed - which uses memory unnecessarily in the meantime. (Careful: calling virtual functions from constructor/destructor is a bad idea!)
Why store a std::unique_ptr in ResourceManager::resources if the resource is going to be shared anyways? This is the usage std::shared_ptr and std::weak_ptr were made for!

Example:
#include <memory>
#include <unordered_map>

class Resource {
public:
    Resource(const std::string&) {}
    virtual ~Resource() {}
};

class Texture : public Resource {
public:
    int width;
    int height;
    int channels;
    uint8_t* data;

    Texture(const std::string& path) : Resource(path) {
        load(path);
    }

    virtual ~Texture() {
        // if needed for whatever reason
        unload();
    }
protected:
    void load(const std::string& path) {
        // loading logic in here
    }

    void unload() {
        // unloading logic in here
    }
};

class ResourceManager {
public:
    template<typename T>
    std::shared_ptr<T> load(const std::string& path) {
        static_assert(std::is_base_of<Resource, T>::value, "T must inherit from Resource");

        auto res = resources[path].lock();
        if(!res) {
            // assuming constructor loads resource
            resources[path] = res = std::make_shared<T>(path);
        }

        auto return_value = std::dynamic_pointer_cast<T>(res);
        if(!return_value) {
            throw std::runtime_error(std::string("Resource '") + path + "' is already loaded as another type");
        }
        return return_value;
    }
private:
    std::unordered_map<std::string, std::weak_ptr<Resource>> resources;
};

Some benefits of this design:

Resource cleanup is handled by std::shared_ptr.
Resources are unloaded as soon as they aren't needed anymore.
No dangling references!
Additional error handling if resource with the same name as another resource type is already loaded
ResourceFree isn't needed anymore, because the usual destructor already does all the work.

Other considerations

path gets passed around a lot. While I get that the high-level caller would uses that one, it might be more fitting to pass a stream (or maybe file handle / pointer to a byte array / a gsl::span) to the resource constructor. This way, the resource doesn't have to care whether it's loaded from disk, or from a zip file, or from a network stream, or from (somewhere else). However, this would actually require an ID to uniquely identify a resource (how would a path refer to a resource transmitted over the net?) - which by itself isn't a bad idea if used correctly.


Your whole code can be reduced to this.

/* secsToDHMS()
 * Author Gary Green
 * http://stackoverflow.com/users/63523/gary-green
 */
function secsToDHMS(s)
{
  var x = [86400, 3600, 60, 1],z,i=-1;
  while (z=x[++i])
        x[i] = ("0" + parseInt(s / z,10)).slice(-2),
        s %= z;

    return x.join(':');
};

(function() {

    var currentDate      = new Date();
    var endDate          = new Date('March 30, 2012 18:10:00');
    var secsToGo         = (new Date(endDate - currentDate)).getTime() / 1000;
    var countdownElement = document.getElementById('countdown');

    var timer = setInterval(function() {

        if (--secsToGo < 0) {
            clearInterval(timer);
            return;
        }

        countdownElement.innerHTML = secsToDHMS(secsToGo);

    }, 1000);

})();

Fiddle: http://jsfiddle.net/xg63V/4

Compressed version 311 bytes

(function(){var d=(new Date(new Date("March 30, 2012 18:10:00")-new Date)).getTime()/1E3,
f=document.getElementById("countdown"),g=setInterval(function(){if(0>--d)clearInterval(g);
else{for(var a=d,b=[86400,3600,60,1],c,e=-1;c=b[++e];)b[e]=("0"+parseInt(a/c,10)).slice(-2),
a%=c;f.innerHTML=b.join(":")}},1E3)})();


Checking to see if array can be sorted using only one operation

You have to make some functions.

You can start off with swap, reverse and is_sorted.
These are simple one or two liners:

def swap(array, i, j):
    array[i], array[j] = array[j], array[i]
    return array

def reverse(array, i, j):
    return array[:i] + array[j:i-1:-1] + array[j+1:]

def is_sorted(array, length):
    return all(array[i] < array[i+1] for i in xrange(1, length))

This keeps things nice and DRY.
'Cause repeating your self is bad.

Next you can do with a get_indexs.
This will use the loops you have at the moment, to make the code simpler, you can make two comprehensions.
This can be to get ups and downs.
And from this you can get ups, downs, first_index, last_index and swap_i.

Since you currently create first_index in a for loop, it's not guaranteed to be created,
and so we'd have to create it before the loops too.
This can cause the following function:

def get_indexs(array, length):
    first_index = None
    later_index = None
    swap_i = None
    range_ = xrange(1, length + 1)
    up = [i for i in range_ if array[i - 1] < array[i] > array[i + 1]]
    down = [i for i in range_ if array[i - 1] > array[i] < array[i + 1]]

    if up:
        first_index = up[-1]
        swap_i = up[0]
    if down:
        later_index = down[-1]

    return (
        len(up),
        len(down),
        first_index,
        later_index,
        swap_i,
    )

Next you'd want to change your massive if-else block.
You do a check if the output of the function is sorted, and you manually print everything.
Instead if you make a function that returns the three strings that you need, and you use these to test the array,
then you can significantly reduce the complexity of your program.
Take:

def get_command(array, length):
    ups, downs, first_index, later_index, swap_i = get_indexs(array, length)
    if downs == ups == 2:
        return 'swap', swap_i, later_index
    elif downs == ups == 1:
        if first_index == 1 or later_index == length:
            return 'swap', swap_i, later_index
        else:
            command = 'swap' if first_index - later_index == -1 else 'reverse'
            return command, first_index, later_index
    elif ups == 1 and downs == 0:
        return 'reverse', first_index, later_index
    return False

The final function that you'd want to make is a main.
You'd want to move all your global declarations into it.
Such as n = int(raw_input()).
You'd then want to move the little section that you copied and pasted on all your previous if-else's.
To be able to easily use the functions that you'd made above you'd want to add a single variable to the global scope too, it's just a simple dictionary that will hold the functions.
This could result in the following simple function:

COMMANDS = {
    'swap': swap,
    'reverse': reverse
}

def main():
    n = int(raw_input())
    ar = map(int, raw_input().strip().split())
    ar.insert(0, -1)
    ar.append(1000001)

    command = get_command(ar, n)
    if command:
        c, i, j = command
        ar = COMMANDS[c](ar, i, j)
        if is_sorted(ar, n):
            print 'yes'
            print '{} {} {}'.format(*command)
            return None
    print 'no'

Your algorithm may be easy to improve, but I think that you have to improve the base of you program.
As you'll end up coping and pasting lots of code all over the place, as you already have.
This code may not be the easiest to read, as optimized code normally isn't,
and may lead to a horrible program, rather than quite a nice one.

Also you say:

  doing nothing (i.e. it is already sorted)

But it prints 'no', if I enter a sorted list.

5
1 2 3 4 5
no

Should that not just be a 'yes' rather than a 'no'?


Evaluating a completely parenthesized arithmetic expression

Use Iterators
The int i and int j are unnecessary parameters in int evaluate(const std::string& expr, int i, int j).
The string class is a standard container class. Standard container classes provide the begin() and
end() functions that provide iterators to the first element and the last element of the container.
This StackOverflow.com Question highlights why iterators are good.

This StackOverflow.com question provides a possible example for finding the last character to process.

Using iterators will be faster than using indexing by integer. In C++11 or later the following loop
will advance the iterator until non-white space characters are found in the string.

for (auto CharInExperession : exper)
{
    if (!isspace(*CharInExperssion)) {
        break;
    }
}

Use Standard C++ functions to check for white space
In the example above isspace() is used, this checks for all white space, not just space so it checks for
tabs, spaces and new lines. See isspace for information on how to use it.

Reduce the Complexity of the Code
There is no reason to have the else clause for if(i == j) {, the code in the else clause can be out-dented
because of the return in the if-then portion.


You should never use gets() to read keyboard input, ever. Use fgets(), where you specify the max size of the buffer. That way, you are protecting yourself from somebody hacking your code.

You don't check input values. It is good practice to not assume a benevolent keyboard user, so, for instance, when a user enters rotatorN = -12128, you get all kinds of interesting behavior in your program.

Using scanf for input is hard to get right and therefore error-prone. Instead, use fgets for all input and then use sscanf to get the contents.

Check the calculated value for rotateSwap so that it falls within the expected range.


You're misusing the term strategy pattern.
Instead of doing this kind of thing:

template <class K, class V>
void Map<K,V>::SetDataStructureStrategy(int ds_type)
{
  if(ds_ != NULL)
  {
    delete ds_;
  }

  if(ds_type == DSType::DYNAMIC_MAP)
  {
    ds_ = new DynamicMap<K,V>;
  }
  else if(ds_type == DSType::ARRAY_MAP)
  {
    ds_ = new ArrayMap<K,V>;
  }
}

The strategy pattern would look something more like this:

template <class K, class V>
void Map<K,V>::SetDataStructureStrategy(DataStructureStrategy * dsStrategy)
{
  this->dsStrategy = dsStrategy;
}

That is, you would have a DataStructureStrategy abstract parent class,
with concrete implementations in subclasses,
for example DynamicMapStrategy and ArrayMapStrategy.

And then, the code to initialize the data structure would look like this:

ds_ = dsStrategy->newDataStructure();

where newDataStructure would be implemented in the specialized subclasses like this:

// implementation of DynamicMapStrategy::newDataStructure
return new DynamicMap<K,V>;

// implementation of ArrayMapStrategy::newDataStructure
return new ArrayMap<K,V>;

In other words:

Your hashmap class shouldn't have to know how a strategy is implemented. At no point should the code have conditional statements on DSType. In fact there's no need for DSType.
The same goes for all the other kind of strategies that you implied: hash strategy, collision strategy. Define a common interface for each strategy that the hashmap wants to work with. Move the implementations of strategies outside of the hashmap, into subclasses of the common interfaces.
These strategies should not change during the lifetime of a hashmap. It wouldn't be efficient to switch the strategy of an existing hashmap. So it would be better to make these strategies required at construction time, and remove the setters.


I am glad to see your method takes a &str instead of a &String or String!
Shouldn't be printing output inside function.
The one function is doing too much. Instead, create two functions, one to convert hex -> bytes, andone to convert bytes -> base64. Note that your comments already declare where functions should be! You could promote those to doc comments, or the function name may be enough.
Don't specify exact types when declaring variables, let type inference handle it. decoded_bytes: Vec<u8> = Vec::new(); should be decoded_bytes = Vec::new();. Note that changed code has very few foo: type lines, mostly for collect where the return type is up to the caller.
Can collect into a Vec<_>, no need to specify item type.
Use chunks instead of reimplementing it. Note that it returns a smaller chunk when not a multiple of the chunk size. hex_to_bytes will crash with odd count of values, I think the previous did as well.
Once operating on an iterator, switch to map and add collect. Avoids need for mutation.
Prefer expect over unwrap. When it crashes you will be thankful.
String::new instead of String::from("").
Traditionally, the Base64 conversion table is a hard-coded constant, not re-created for each call.
The length of the bytes never changes, get it once before the loop and reuse it.
Declare variables as near to usage as they can be. b shouldn't be outside the loop.
Consider rebinding b when it's reset to a brand new value.
Consider getting the result of indexing and storing it into a variable, since it shouldnt change
Instead of checking the length and then indexing, use if let combined with get.
Use chunks again.
No explicit return at end of method.
Use assert_eq!.
Can compare string literal against String, no need to allocate

  Is there a better way to write debug statements?

You may be interested in the log crate, although I'd argue that these printing statements only had any value when the function was being originally developed, and probably don't deserve to stay in as logging either.

  I'm not sure what this one means?

Instead of

let mut b = 1;
b += 1;
b = 5;

You may want to try

let mut b = 1;
b += 1;
let b = 5;

This may help indicate that you deliberately reset the value.

fn main() {
    let b64 = hex_to_base64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
    println!("{}", b64);
}

/// Decode the input string from hex into individual bytes
fn hex_to_bytes(hex_string: &str) -> Vec<u8> {
    let input_chars: Vec<_> = hex_string.chars().collect();

    input_chars.chunks(2).map(|chunk| {
        let first_byte = chunk[0].to_digit(16).unwrap();
        let second_byte = chunk[1].to_digit(16).unwrap();
        ((first_byte << 4) | second_byte) as u8
    }).collect()
}

/// Encode the decoded bytes into Base64
fn bytes_to_base64(decoded_bytes: &[u8]) -> String {
    let mut output = String::new();
    let alphabet: Vec<_> =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".chars().collect();

    for chunk in decoded_bytes.chunks(3) {
        let c0 = chunk[0];
        let b = (c0 & 0xFC) >> 2;
        output.push(alphabet[b as usize]);

        let mut b = (c0 & 0x03) << 4;

        if let Some(c1) = chunk.get(1) {
            b |= (c1 & 0xF0) >> 4;
            output.push(alphabet[b as usize]);

            let mut b = (c1 & 0x0F) << 2;

            if let Some(c2) = chunk.get(2) {
                b |= (c2 & 0xC0) >> 6;
                output.push(alphabet[b as usize]);

                let b = c2 & 0x3F;
                output.push(alphabet[b as usize]);
            } else {
                output.push(alphabet[b as usize]);
                output.push('=');
            }
        } else {
            output.push(alphabet[b as usize]);
            output.push_str("==");
        }
    }

    output
}

fn hex_to_base64(hex_string: &str) -> String {
    bytes_to_base64(&hex_to_bytes(hex_string))
}

#[test]
fn test_hex_to_base64() {
    assert_eq!(
        hex_to_base64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"),
        "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
    );
}


Unloading external DLL library after 10 seconds in order to release file locks

Another, perhaps simpler, option is to locally copy the dll and load the copy.

Then regularly check the original dll for an updated last modified time and then unload the copied dll, make a fresh copy and load the new copy.

Do keep in mind that when debugging a dll has a pdb file associated with it and loading the dll also locks the pdb. You can work around that by making the compiler emit the pdb with a different name each time.

However as is your implementation isn't thread safe. If the timer is about to trigger then action could still be running. Instead you will want to use a ReaderWriterLock, take a read lock when doing action() and a write lock when actually loading and unloading.

Lock.AcquireReaderLock(1000);
try{
    if (!IsLoaded)
    {
        LockCookie cookie = Lock.UpgradeToWriterLock(1000);
        try {
            //someone else may have gotten ahead in the queue
            if (!IsLoaded)
            {
                // ... loads pdf library ...
            }
        } finally {
            Lock.DowngradeFromWriterLock(cookie);
        }
    }
    action();

} finally {
    Lock.ReleaseReaderLock();
}


A possibly-terrible alternative to conditionals full of null checks

I tend to use monads in such situations:

public static TResult With<TSource, TResult>(this TSource source, Func<TSource, TResult> action)
    where TSource : class
{
    if (source == null) return default(TResult);
    return action(source);
}

public static TSource Do<TSource>(this TSource source, Action<TSource> action)
    where TSource : class
{
    if (source != null)
    {
        action(source);
    }
    return source;
}

And then:

c.With(x => x.Class2).With(x => x.Class3).With(x => x.AProperty).Do(x => "Yay!".Dump());


Your code is actually very good.

I'd advice against using OOP there. It's an overused tool which, when not necessary, only makes things more complex. JavaScript works very well without it. I'd recommend a more functional style. So, if you want to make your code more reusable, you could abstract your functions to work with any kind of collection. You could also use existing functions to define others:

function removeFirst(array,obj) {
    array.splice(array.indexOf(obj), 1);
};
function without(array,obj){
    return array.filter(function(element){
        return element !== obj;
    });
};
function count(array,obj){
    return array.length - without(array,obj).length;
};

Then, counting an image would be, for example:

count(images,my_image);

But before I'd suggest checking some functional JavaScript libraries such as underscore.js, which already implement similar functions in very clever manners. Using them in your daily code will make it smaller, simpler, more readable and robust.


Just a couple of suggestions.

First, artists and producers are both persons and a person can be both an artist and a producer (even on their own songs).

Second, more than one persons can work together on a song, but in lots of different roles (backup musician, backup singer, "featuring", "uncredited", or as a member of a groups). So performers and roles would probably look something like:

CREATE TABLE roles (
    role_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    description varchar(100) not null
) ENGINE = 'INNODB';

CREATE TABLE performers (
    performer_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tune_fk INT NOT NULL,
    person_fk INT NOT NULL,
    role_fk INT NOT NULL,
    FOREIGN KEY (tune_fk) REFERENCES tunes(tune_id) ON DELETE SET NULL ON UPDATE CASCADE,
    FOREIGN KEY (person_fk) REFERENCES persons(person_id) ON DELETE SET NULL ON UPDATE CASCADE,
    FOREIGN KEY (role_fk) REFERENCES roles(role_id) ON DELETE SET NULL ON UPDATE CASCADE,
) ENGINE = 'InnoDB';


Breadth First Search implementation in Python 3 to find path between two given nodes

Comments

Provide a docstring, detailing what the code does and returns

Pep-8

When writing Python, it is advised to follow the styleguide. This means snake_case instead of hybridCamelCase for variable.

Another formatting I use is

graph = {
    'A': set(['B', 'C']),
    'B': set(['A', 'D', 'E']),
....
    'F': set(['C', 'E']),
}

Instead of your representation. If ever you change something to this, the diff of your code versioning system will be a lot clearer and simpler. (note the trailing comma after the last entry)

Separate presentation with the calculation.

Use a function traversing the graph, and returning the path, and another one to present the result (if needed). This way, you can also write unittests that don't need to mock print to test the algorithm

Use an exception to signal something exceptional

Instead of just printing that there is no path, you can signal this by returning None or raising an exception

class NoPathException(Exception): pass

Data structure

instead of keeping a separate dict with the path, it is easiest if you stack the queue with the node and the path used to reach it so far. That make your effort a lot easier. There is no need to keep the dict, but an ordinary set with the nodes visited should suffice.

Minimize the indents

To minimize the number of indents and keep your line length under control, instead of

for item in loop:
    if condition:
        do_something()

you can do:

for item in loop:
    if not condition:
        continue
    do_something()

Especially with a lot of nested conditions, this is a lot more compact.

Complete algorithm

def bfs2(graph, start, goal):
    """
    finds a shortest path in undirected `graph` between `start` and `goal`.
    If no path is found, returns `None`
    """
    if start == goal:
        return [start]
    visited = {start}
    queue = deque([(start, [])])

    while queue:
        current, path = queue.popleft()
        visited.add(current)
        for neighbor in graph[current]:
            if neighbor == goal:
                return path + [current, neighbor]
            if neighbor in visited:
                continue
            queue.append((neighbor, path + [current]))
            visited.add(neighbor)
    return None  # no path found. not strictly needed

if __name__ == '__main__':
    graph = {
        'A': set(['B', 'C']),
        'B': set(['A', 'D', 'E']),
        'C': set(['A', 'F']),
        'D': set(['B']),
        'E': set(['B', 'F']),
        'F': set(['C', 'E']),
    }
    path = bfs2(graph, 'D', 'F')
    if path:
        print(path)
    else:
        print('no path found')


Everything you might want to know about an element

I have written the following to help scrape several of the bits of information I need to proceed.

If this is for development purposes, for gathering information about an element and not actually related to your application, then you won't need this at all. The browser dev tools has a watch panel (F12 -> Sources -> First panel on the right side). You can simply pop in expressions and get their value there.

Now if it is for development, then this plugin is just the opposite of performant. Every time you call jquery.info(), all of these calculations run. That's fine if you actually use all of them, but if not then everything is unnecessary. I would suggest that you just create utility functions and call on a need-to-know basis.

Whenever you call $('.selector').info(), the this inside your function is actually a jQuery set that may contain zero or more matched items. But your logic only assumes one item in the set. How so?

Take $el.offset().left. When the set is empty, the return of offset will not be an object. This means accessing left will throw an error. As shown in the following:

// Access property left of undefined... or something not an object.
$('.non-existent-element').offset().left

Also, the order of the elements in the set is not to be relied upon. You might be aiming for a specific element, but there might accidentally be another element that matches your selector and jQuery might pick it up first. What's the problem? Methods like offset only pick up data from the first item in the set. If your element isn't that item, you might be grabbing the wrong data.

// Returns 8px top when black is clearly 200px down...
// That's because there's 4 other divs you didn't expect.
alert($('.color').offset().top);
.color{
  width: 50px;
  height: 50px;
}

.invi{
  visibility: hidden;
}

Red

Blue

Green

Yellow

Black

  /* :compute the box-modal a,b,c,d with {x,y} values: */
  /* a----b */  this.a = { x:this.x, y:this.y };
  /* |    | */  this.b = { x:this.x+this.w, y:this.y };
  /* |    | */  this.c = { x:this.x, y:this.y+this.h };
  /* c----d */  this.d = { x:this.x+this.w, y:this.y+this.h };

Your a, b, c and d, width, height, x and y can be retrieved from getBoundingClientRect.

this.winH = Math.floor(this.$win.height());
this.winW = Math.floor(this.$win.width());
this.docH = Math.floor(this.$doc.height());
this.docW = Math.floor(this.$doc.width());
this.top = this.$win.scrollTop();

This will return false data when the function was called, then the window is resized or scrolled.


So, the most interesting bits about this code are the wildly differing styles throughout. It seems as it's almost copy-and-pasted from several sources. The reason I bring this up is because consistency is a hallmark of clean and maintainable code. A few things I noticed:

There's a debunked use of "double-checked locking" to attempt to use a lazily-instantiated singleton. Two things with this: A. This class doesn't have state and could be static to begin with, and thus do not need to worry about instances at all, and B. There's a very easy way these days to have a lazy singleton: the Lazy<T> class. You'll see its usage below.
There's a mish-mash of ASCIIEncoding.ASCII and new UnicodeEncoding(). The canonical way to access predefined encodings is through static members of the Encoding class: Encoding.ASCII and Encoding.Unicode.
Path.Combine() is wisely used to, of course, combine paths. But then string concatenation is used to pop an extension on the file name. Path.ChangeExtension() exists for just this task.
x.Close() isn't needed if you wrap your IDisposable resources in using blocks. This also has the benefit of guaranteeing disposal/closing in the case of an exception (it's syntactic sugar for a try..finally construct`.
There's a mix of using and not using var for variable declarations. Since the latter is less than the former, standardize on just using the actual type name for declarations.
I added two more - you don't need to read/write the file byte by byte. These are streams for a reason, and .NET gives us a handy method CopyTo to take care of the details. Also, CreateEncrpytor and CreateDecryptor return IDisposable-implementing classes, so I extracted them into their own usings.

Putting all that together, the class now looks like (note that I went with Lazy<T> rather than static class):

public sealed class Class1
{
    private static readonly Lazy<Class1> instance = new Lazy<Class1>(() => new Class1());
    public static Class1 Instance => instance.Value;

    public bool EncryptFile(string path)
    {
        string ext = Path.GetExtension(path).Replace(".", string.Empty);
        string filename = Path.GetFileNameWithoutExtension(path);

        byte[] b = Encoding.ASCII.GetBytes(ext);
        string encrypted = Convert.ToBase64String(b);
        string newPath = path.Replace(Path.ChangeExtension(filename, ext), filename + "_" + encrypted + ".vik");

        try
        {
            string password = @"vik12389"; // Your Key Here
            byte[] key = Encoding.Unicode.GetBytes(password);

            string cryptFile = newPath;
            using (FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create))
            using (RijndaelManaged RMCrypto = new RijndaelManaged())
            using (ICryptoTransform ct = RMCrypto.CreateEncryptor(key, key))
            using (CryptoStream cs = new CryptoStream(fsCrypt,
                ct,
                CryptoStreamMode.Write))
            using (FileStream fsIn = new FileStream(path, FileMode.Open))
            {
                fsIn.CopyTo(cs);
            }

            File.Delete(path);

            return true;

        }
        catch(Exception e)
        {
            return false;
        }
    }

    public bool DecryptFile(string path)
    {
        string ext = Path.GetExtension(path).Replace(".", string.Empty);
        string filename = Path.GetFileNameWithoutExtension(path);

        string[] splitFilename = filename.Split('_');

        byte[] b = Convert.FromBase64String(splitFilename[1]);

        string decryptedfileext = Encoding.ASCII.GetString(b);

        string newPath = path.Replace(Path.ChangeExtension(filename, "vik"), splitFilename[0] + '.'+ decryptedfileext);
        try
        {
            string password = @"vik12389"; // Your Key Here

            byte[] key = Encoding.Unicode.GetBytes(password);

            using (FileStream fsCrypt = new FileStream(path, FileMode.Open))
            using (RijndaelManaged RMCrypto = new RijndaelManaged())
            using (ICryptoTransform ct = RMCrypto.CreateDecryptor(key, key))
            using (CryptoStream cs = new CryptoStream(fsCrypt,
                ct,
                CryptoStreamMode.Read))
            using (FileStream fsOut = new FileStream(newPath, FileMode.Create))
            {
                cs.CopyTo(fsOut);
            }

            return true;

        }
        catch (Exception e)
        {
            return false;
        }

    }

}


Program to find the largest odd number among three variables

And for those who love comprehensions...

def max_odd(*args):
     return max(x for x in args if x%2)


Given N*N matrix, rotate it by 90 degree to left and right without extra memory

You ask many questions on CodeReview, which in itself is good, but you have to start helping the reviewers actually review your code. You have this habit of dumping code and expecting a review. It does not work that way (very well). For a start, let's review the ideal process for a 'real' review:

you present neat and working code for review.
you include a description of the context of the code - what it does, why it is needed, and what constraints it has.
you provide some specifications or documentation for any complicated or significant algorithms
the reviewer reviews the code, not only for neatness, and style, but to:

check the code works the way it is supposed to (by visual inspection)
suggest alternative approaches that may achieve the same results faster or in a better way
suggest alternative approaches that may produce different results but may be better for other reasons

signs off that the code is:

good (or great and gives you a high five)
good enough but has some future anticipated improvements
not good enough and needs to be fixed then resubmitted

The details, descriptions, references and specifications you provide with the request is essential if the reviewer is going to give a decent review.

On Code review, the process continues with:

upvoting answers that are helpful (and down-voting those that are not).
accepting answers that (among other answers) best address your concerns.

Your question above is lacking any description of what the code is supposed to do, and how it does it. All you do say is:

I want hints and reviews
it works
what is the complexity

As a result, the only specification available and description of what the code should be doing, is what the code actually does. Or the title of the post....

Bottom line is that you have only given a fraction of what is needed for a good review, so, I will take a stab at doing a review with similar feedback....

A good alternative approach for your code is:

public static void rotateByNinetyToLeft(int[][] m) {

    int e = m.length - 1;
    int c = e / 2;
    int b = e % 2;
    for (int r = c; r >= 0; r--) {
        for (int d = c - r; d < c + r + b; d++) {
            int t   = m[c - r][d];
            m[c - r][d] = m[d][e - c + r];
            m[d][e - c + r] = m[e - c + r][e - d];
            m[e - c + r][e - d] = m[e - d][c - r];
            m[e - d][c - r] = t;
        }
    }
}

This approach is O(n) time complexity (n is the number of pixels in the matrix), and O(1) space complexity

I have tested this and it works.

You can use the right-handed approach for rotateByNinetyToRight


Draft version of wind farm design software

I suspect copy.deepcopy is costing you much time; try to avoid it if possible.

Also you are only copying self.list_for_direction[wd], is it necessary to do it multiple time for ws in wind_speed_index?

I try at my best to guess what you are trying to achieve and do not guarantee my code would do exactly what you want.  Here the dummylist is no longer needed except for self.list_for_speed[wd][ws].append(dummylist).  Unless you really need self.list_for_speed later and it is important that those sharing the same wd are distinct object, I am afraid you can't save much time doing so many copy.deepcopy.

One thing that confuses me is that you have nested for WT in dummylist and for ready in dummylist.  And you change WT[6] when it is "NO_deficit" in the first for-loop.  Say you are at the i-th iteration in the first for loop and the j-th iteration in the second for-loop.  If j>i, it is possible that you have ready[6] being "NO_deficit". I assume this is not what you want.

def U_Ct(OBJ,WT6,wind_speed):
    if WT6 == 'NO_deficit':
        deficit_current = 0.0
    else:
        deficit_squared = sum([i**2 for i in WT6])
        deficit_current = sqrt(deficit_squared)
    U = wind_speed*(1-deficit_current)
    _Ct = OBJ.team.rna_analysts.get_Ct(U)
    return U,_Ct

def get_turbine(WT,upWT):
    '''  WT is a value in the dummylist
    upWT is the WT[3] where WT is from the dummylist
    '''
    if WT[6] == 'NO_deficit':
        WT[6] = [0.0]
    for ready in WT:
        if upWT[0] == ready[0]:
            upWT[6] = ready[6]
    current_turbine = WT
    upwind_turbine = upWT
    return current_turbine,upwind_turbine

for wd in wind_direction_index:
    for ws in wind_speed_index:
        dummylist = copy.deepcopy(self.list_for_direction[wd])
        self.list_for_speed[wd][ws].append(dummylist)
        wind_speed = self._wind_speeds[ws]
        for WT in self.list_for_direction[wd]:
            for upWT in WT[3]:
                current_turbine,upwind_turbine = get_turbine(WT,upWT)
                if len(current_turbine[3])!=0:
                    # What does this function do? It doesn't return anything
                    self.calculate_deficits(current_turbine,upwind_turbine,wind_speed)
            U,_Ct = U_Ct(self,WT[6],wind_speed)
            self.local_wind_speeds[WT[0]][wd][ws] = [U,_Ct]


Uncompress archive, check contents, add missing files, recompress archive

Remove unecessary code
myDirList is assigned but never used, delete it:
myDirList = os.chdir('/home/pi/python/chap9OrganizingFiles/shutildir/')

You do not need to build a list as:
for dirList in os.listdir(os.getcwd()):
        myFL.append(dirList)
for listItem in myFL:

You can iterate over os.listdir(os.getcwd()) directly:
for listItem in os.listdir(os.getcwd()):


Project Euler no. 17: Counting letters to write the numbers from 1 to 1000

Aside from the repetitive logic in the code to handle numbers greater than a hundred, the solution is not bad.  There are many observations that could lead to improvements, though.

You don't need to build the strings themselves; you just need to sum their lengths.  In particular, since strings are immutable, += is relatively costly.  (Your solution is still fast enough, though.)
The challenge never requires you to treat 0 as "zero".  You can therefore simplify some logic by mapping 0 to an empty string.
The ranges 0 < num <= 20, 21 <= num <= 99, 100 <= num <= 999, and num == 1000 are mutually exclusive.
You can reduce repetition by using recursion.

Solution

numbers_dict = {
    n: len(word) for (n, word) in {
        0: "",
        1: "one",
        2: "two",
        3: "three",
        4: "four",
        5: "five",
        6: "six",
        7: "seven",
        8: "eight",
        9: "nine",
        10: "ten",
        11: "eleven",
        # ...
        90: "ninety",
    }.iteritems()
}

def num_length(n):
    if n <= 20:
        return numbers_dict[n]
    elif n < 100:
        ones = divmod(n, 10)
        return numbers_dict[10 * tens] + num_length(rest)
    elif n < 1000:
        hundreds, rest = divmod(n, 100)
        return num_length(hundreds) + len("hundred") + (
            len("and") + num_length(rest) if rest else 0
        )
    else:
        thousands, rest = divmod(n, 1000)
        return num_length(thousands) + len("thousand") + num_length(rest)

print(sum(num_length(n) for n in range(1, 1001)))

You could also use numbers_dict for memoization:

def num_length(n):
    if n in numbers_dict:
        return numbers_dict[n]
    elif n < 100:
        tens, rest = divmod(n, 10)
        numbers_dict[n] = numbers_dict[10 * tens] + num_length(rest)
        return numbers_dict[n]
    elif n < 1000:
        hundreds, rest = divmod(n, 100)
        return num_length(hundreds) + len("hundred") + (
            len("and") + num_length(rest) if rest else 0
        )
    else:
        thousands, rest = divmod(n, 1000)
        return num_length(thousands) + len("thousand") + num_length(rest)


Sum of absolute difference of values and corresponding indices of an array

First of all, I want to say this is really well presented. It just looks neat, with docstrings and comments and such. If you really want to perfect it, check the Python conventions in PEP 8 and linked documents. For example,

  An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

and

  The docstring is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...".

I also very much appreciate the case analysis that has gone into the code to define those four cases, and so to reduce the naively quadratic function to a linear one. (Refering back to comments, that case analysis would not be at all amiss in a comment just after the docstring explaining the internal logic of the function)

Because, per the code and your case analysis, max1 and min1 always contain the same data, you could make the code shorter and reduce its space requirements by only having one of those. (And likewise for max2 and min2) However, see the next section.

In terms of the code itself, I suggest getting rid of those arrays. If they are only filled so that you can reduce them to a single maximum or minimum value, you might as well just track the rolling maximum or minimum as you go. This definitely saves space and probably saves time.

I would name the rolling reductions max_sum and max_difference rather than max1 and max2.

In terms of testing examples, do look for pathological cases. One case that always deserves to be checked, although it's not always obvious what the behaviour should be, is the case of an empty list.

Finally, it is generally worth using Python 3 in preference to Python 2 for new code, and especially practice code.


Does my Game class have too many responsibilities?

I like to trash people when their classes do too many things.  I was disappointed when I saw your class because it is not so bad.

However, I don't think this class should check if the display did open.  You should only create the Game once you know that the display is ready.

I'm not sure Game is an appropriate class name.

Naming member variables starting with an underscore comes from some other language; it is not standard Java.

You write too many comments.  Let the code speak for itself and you won't have to worry about keeping the code and the comments in sync.

The comment at the beginning at the class is clearly deprecated.
// schedule display to update @ 60 fps might not be true.


Generating a musical scale from a root note

Yikes — the global variables make this spaghetti code.  Functions should make it obvious what their input parameters are, and return their output values.  You'd be better off lumping everything into one main() function than using global variables.  Ironically, the two variables that should have been global constants — chromatic and scales — weren't.

It is customary to put main() last, and helper functions first, so that you don't have to write forward declarations.

You used std::find() and std::distance(), so you should #include <algorithms> and <iterator>.  I suggest listing your includes alphabetically.

Behaviour

Please enter your root note and scale:
F# Major

root scale: F# Major

C D E F G A B

If the rootnote is not found in chromatic, you should handle that case instead of blindly proceeding based on chromatic.end().

Please enter your root note and scale:
D Major

root scale: D Major

D E Gb G A B Db

Those enharmonic equivalents will sound the same, but those should technically be F♯ and C♯.

Please enter your root note and scale:
null blah

root scale: null blah

Making the user enter the magic word "null" as the root note to exit the program is weird.

Suggested solution

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <sstream>
#include <string>
#include <vector>

const std::vector<std::string> chromatic = {
    "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"
};

const std::map<const std::string, const std::vector<int>> degrees = {
    {"Major",       { 0, 2, 4, 5, 7, 9, 11, 12 }},
    {"Minor",       { 0, 2, 3, 5, 7, 8, 10, 12 }},
    {"Harmonic",    { 0, 2, 3, 5, 7, 8, 11, 12 }},
    {"Melodic",     { 0, 2, 3, 5, 7, 9, 11, 12 }}
};

std::string scalenotes(const std::string& rootnote, const std::string& scale) {
    int root = std::distance(chromatic.begin(), std::find(chromatic.begin(), chromatic.end(), rootnote));
    if (root >= chromatic.size()) {
        return "";
    }
    std::stringstream ss;
    for (int i : degrees.at(scale)) {
        ss << chromatic[(root + i) % chromatic.size()] << " ";
    }
    return ss.str();
}

std::stringstream ask(const std::string& question) {
    std::string line;
    std::cout << question;
    std::getline(std::cin, line);
    return std::stringstream(line);
}

int main()
{
    std::string rootnote, scale;
    while (ask("Please enter your root note and scale: ") >> rootnote >> scale) {
        std::cout << "\nroot scale: " << rootnote << " " << scale
                  << ": " << scalenotes(rootnote, scale) << "\n\n";
    }
}


It is nice that you have divided the parsing and the actual calculation over the InputParser and the Calculator.

I think your InputParser can be improved at some points :

Using a regular expression to extract the separator would reduce the size of your InputParser and the large number of methods needed to get the separator.
I would also include the splitting of the input in the parser, so you can return only the numbers. The user of the parser does not really need to know which separator was used.
toInt throws an exception if the string can not be converted to an Int, which you don't handle. More ideomatic Scala would be to return an Option, Try, ...
If you add more functionality to the InputParser, you probably should also create unit tests for the InputParser class.

My attempt to improve your InputParser :

class Parser {
  private val defaultSeparator: String = ",|\n"

  // parse now returns an Option[List[Int]]
  // -> invalid input now returns None (eg parse("foo"))
  def parse(input: String): Option[List[Int]] = {
    input match {
      case "" => Some(List(0))
      case SeparatorNumbers(sep, numbers) =>
        val separator = sep.map(escapeSeparator).getOrElse(defaultSeparator)
        val stringNumbers = numbers.split(separator).toList
        // stringNumbers.map(...) is of type List[Option[Int]]
        // the sequence function below turns this into Option[List[Int]]
        // (you could also use Scalaz for sequence (or traverse), but
        // that is probably overkill if you only use it here)
        sequence(stringNumbers.map(i => Try(i.toInt).toOption))
      case _ => None
    }
  }

  // not explicitly mentioned in the requirements
  // make multiple separators possible (eg "//[:|;|,]\n1:2;3.4")
  private def escapeSeparator(sep: String) =
    sep.split("""\|""").map(java.util.regex.Pattern.quote).mkString("|")

  // an extractor object which uses a regular expression
  // pattern matching with SeparatorNumbers gives an optional separator
  // and the numbers (still as one string)
  object SeparatorNumbers {
    // regular expression with two capture groups for separator and the rest
    private val Extract = """(?s)^(?://\[?(.+)\]?\n)?(.*)""".r

    def unapply(input: String): Option[(Option[String], String)] =
      input match {
        // if no separator is found, sep is null
        // Option(sep) will then be None
        case Extract(sep, numbers) => Some(Option(sep), numbers)
        case _ => None
      }
  }
}

// possible implementation to sequence List[Option[A]]
def sequence[A](listO: List[Option[A]]) : Option[List[A]] =
  listO.foldLeft(Option(List.empty[A])) {
    case (None, _) => None
    case (_, None) => None
    case (Some(list), Some(elem)) => Some(elem :: list)
  }.map(_.reverse)

Your Calculator class could pretty mutch stay the same, you only need to handle Option[List[Int]] instead of List[Int].

val p = new Parser

def add(input: String) = {
  p.parse(input).map(_.filter(_ < 1001).sum)
  // now Option[Int], depends how you want to handle invalid input
}


Check SMART status on MacOS and pop up alert

Some suggestions:

A direct string comparison test may be flaky especially if the string contains multiple space characters. I can think of three alternatives:

Use regex matching: this can be achieved by the =~ operator inside [[ ]]: if [[ ! "$A" =~ Verified ]].
Use awk:

A=$(diskutil info disk0 | awk '/SMART Status:/{print $NF}')
if [ "$A" != 'Verified' ]
# ...

Check exit status instead of output:

if sudo smartctl -H -q silent /dev/disk0
# ...

Use more descriptive names: smart_status_text is more self-evident than A.
Properly format your code: indent the commands inside the if block and don't leave a blank line after then.


Depending on your requirements (is javascript allowed, which browsers can be used), I'd go for a CSS only solution.

CSS:

table.zebra tr:nth-child(odd) {
    background-color: #EFF4FA;
}

table.zebra tr:nth-child(even) {
    background-color: #F7FAFD;
}

PHP:

    Previous Plan:
    {{ form_row(form.prev_plan) }}

    Previous Server:
    {{ form_row(form.prev_srv) }}

Here's the catch:

You can't use these wonderfull selectors in every browser (IE < 9, I'm looking at you!). Only in most of them. There's a great explanation of the selector at w3c and an overview over browsers supporting it at caniuse.

And if you still want to use CSS3 selectors and need early IE support, there's javascript providing it (e.g. selectivizr - I never used it, but it's easy to find alternatives). Just search for "css3 selectors in IE" in your favorite search engine.

I guess this still doesn't solve your text overlay issues, but for that, you'd best point to an example page.


Finding the number of moves a knight can perform while standing on a given square

Never use existing function names for new functions
Python already has a function called map() Defining your new map() function can cause a lot of confusion, and undefined behaviour in your program.
By cheating
Since you have asked for an alternate solution, here it is
Being a chess engine developer, I would never calculate something trivial like the number of knight attacks since a simple array of size 64 with the pre-calculated ones can easily work. All you need is a simple function that converts a square like a1 to 0 and h8 to 63.
Here is the implementation,
def str_sq_to_int(sq):
    return (ord(sq[0])-97) + ((ord(sq[1])-49) * 8);

def knightAttacks(cell):
    attacks = [
        2, 3, 4, 4, 4, 4, 3, 2,
        3, 4, 6, 6, 6, 6, 4, 3,
        4, 6, 8, 8, 8, 8, 6, 4,
        4, 6, 8, 8, 8, 8, 6, 4,
        4, 6, 8, 8, 8, 8, 6, 4,
        4, 6, 8, 8, 8, 8, 6, 4,
        3, 4, 6, 6, 6, 6, 4, 3,
        2, 3, 4, 4, 4, 4, 3, 2
    ]
    return attacks[str_sq_int(cell)]

The explanation is simple, the function str_sq_to_int() takes a square like 'a1' and returns an index using the ASCII value of the character to calculate the index. You can also use a simple dictionary to map each square to an index, but this one is easy
Then, it uses a pre-calculated set of values, to return the correct answer.


String Trimmer and trimmed Input routine

typename std::basic_string<Ch, Tr, Alloc>::const_iterator e = str.end();
...

// Query: this loop looks u-g-l-y. Can it be less ugly?
  while( b != e ) {
    e--;
    if(!std::isspace(*e, loc)) {
      e++;
      break;
    }
  }

This looks weird and tends to go UB.

1) e = str.end();

2) e--; /* it's better to use --e in this case */ you move one more far position after end()!!!

3) std::isspace(*e, loc) <--- UB, accessing the memory that haven't been allocated

If you need to find the first and the last spaces in the string, use this:

b = find_if(str.begin(),  str.end(),  isspace_predicate);
e = find_if(str.rbegin(), str.rend(), isspace_predicate);


In my opinion, "buying" should be encapsulated in it's own method that needs to know the symbol, cash and coin amounts.

Since buying is transactional and both actions need to happen or be rolled back, I think it's a good candidate for it's own method and shouldn't be mixed with converting currencies whioch in my opinion is a pre-requisite to buying. If, for example, there is an error with converting the currencies, buy shouldn't be called at all.

Moreover, there may be side effects to buying like managing stock and dispatching the goods so that makes it an even better candidate for it's own method.

Maybe like this:

def buy(symbol, cash_amt, coin_amt)
  # Both coin and cash amount need to be passed
  raise ArgumentError unless coin_amt && cash_amt

  withdraw_cash(cash_amt)
  @transactions << Transaction.new(symbol, coin_amt, market_price)
end

def market_price(symbol)
  @exchange.price_by_symbol(symbol)
end

def buy_in_cash(symbol, cash_amt)
  coin_amt = cash_to_coin(cash_amt, market_price(symbol))
  buy(symbol, cash_amt, coin_amt)
end

def buy_in_coin(symbol, coin_amt)
  cash_amt = coin_to_cash(coin_amt, market_price(symbol))
  buy(symbol, cash_amt, coin_amt)
end


The code in the post (and in WolframH's answer) has a bug:

>>> find_pairs_with_given_difference([1], 0)
[[1, 1]]

There is no pair of items [1, 1] in the input array.


jQuery animation and rotation effects for a WordPress site

I'm going to go through a few main points here about your code and at the bottom I'll have a "what I would change" section with inline comments. Do not be overwhelmed by the size of this book, I prefer to be on the side of too much information than too little.

- Cache your selectors: Probably the most important thing you can do for your code now. As a rule of thumb, if you use a selection more than once, you should cache it. What happens when you use $("someElem") is jQuery queries the DOM to try and find elements that match. So imagine that every time you do that it runs a search. Would it be better if you could save the search results? This way you can look and play with them whenever you want.  Ex.:

$("#sb-container div").css("transform", "rotate(0deg)"  );
$("#sb-container div").css("-webkit-transform", "rotate(0deg)"  );

//Should be like this:
var sbContainer = $("#sb-container div"); //Saved my search to a variable, which I use later.
sbContainer.css("transform", "rotate(0deg)"  );
sbContainer.css("-webkit-transform", "rotate(0deg)"  );

- You can use $ in Wordpress: If you have your code in the footer (which you should be doing) what you'll want to do is wrap it in a IIFE. "What the hell is that?" you may ask. A basic syntax looks like this:

(function () {
    //Code goes in here.
})();

You'll see several variations of this all over the internet as you read to find out more. The one I recommend you use in this case is like this:

;(function ($, window, document) {
    //Code goes here and the $ belongs to jQuery
})(jQuery, window, document);

So lets break this down. The ; in the front is a safety net against unclosed scripts, which can be common if you use plugins in Wordpress, or if you concat and minify your files it will protect you from your function becoming an argument.

Then we pass in $, window, and document. We pass in $ and at the bottom assign it to jQuery. So now in this function, no matter what value the $ carried outside, in here it's jQuery. Then we pass in window and document. These are optional in your case, but a good idea since you do use references to window in your code. It saves window as a local variable, and also will be good when you minify your code as the window reference can be changed to something like a or foo automatically.

Now keep in mind there might be times where you have to put your script in the header. Modernizr is an example of this. Then you'll probably end up using the document.ready. Don't sweat because all you have to do is this:

jQuery(document).ready(function( $ ) {
    //Code goes here and $ will belong to jQuery.
});

I wouldn't rely on $.noConflict

- Chaining: As pointed out in your question, you should be using something like that. jQuery is particularly good at this and you should make the most of it. Ex.:

$("#someElem").css("background-color", "#fff").animate({"right":"1%"}, "slow").draggable();

I apply all this stuff to this selector, one after the other. If I want to continue chaining but change my selectors, I can use stuff like .find() and continue with my methods.

- Save function calls: If you read the jQuery source code you'll see that shortcut methods like .click(), .scroll(), and etc. all reference the .on() method. All they do is basically call the .on() method with some variances. Well why not just go straight to the meat and potatoes? Check this out:

$("#foo").click(function() {
    //Do your awesomeness
});

//That does the same thing as this:
$("foo").on("click", function() {
    //Do your awesomeness even awesomener.
});

I highly recommend, if you're going to use jQuery on a regular basis, that you take some time and read through the source code of the methods you're using. To find them quickly just use CTRL+F and type method:. That should jump you straight to what you want to know. This way you can understand what and how you are doing things, and even find better ways to do them on your own.

-Playing with visible elements: You're if statements from what I can tell are trying to detect scroll position and etc. I highly recommend you check out this tiny plugin. It basically detects if an element is visible or not at any given time. This may or may not help you out but I just thought I'd throw that out there.

-Things I'd write differently: Here's an example of all of this summed up into your actual code. I've included comments so you can relate to the reading part.

;(function ($, window) { //Here's our IIFE giving us full $ power
    //Right here at the top we declare our selection variables to be used throught the code.
    //Don't forget to replace your selectors with the appropriate variable name.
    var main = $(".main"),
        sbContainer = $("#sb-container"),
        sbContainerDiv = sbContainer.find("div");

    function animate() { //Write your code only once, and call it when you need it.
        sbContainerDiv.css({ //You should apply a class instead of doing all of this in here like this.
            "transform": "rotate(0deg)",
            "-webkit-transform": "rotate(0deg)",
            "-ms-transform": "rotate(0deg)",
            "-moz-transform": "rotate(0deg)",
            "-o-transform": "rotate(0deg)"
        });

        main.animate({"right":"1%"}, "slow");
    }

    if ( window.width() < 960) {
        main.animate({"top":"22%"});

        //This use of .toggle() was deprecated in jQuery 1.8 and removed in 1.9
        //Consider doing this differently
        //If you provide me with more details on this I can help you come up with a different solution
        $('#tblcontents').toggle(function() {
            main.fadeOut(1000);
        }, function() {
            main.fadeIn(1000);
            main.animate({"top":"22%"});
        });
    } else {
        $('.menu-button').on('click', function() {
            animate(); //Here we call our previously set animate function
        });
    }

    //Refer to the previous toggle comment.
    $('.toggle_div').toggle(function() {
        main.animate({"right":"50%"}, "slow");
    }, function(){
        main.animate({"right":"1%"}, "slow");
    });

    $(".pulse").effect("pulsate", { times:100 }, 2000).on('click', function() {
        $(this).effect().stop(true, true); //In a callback function, 'this' refers to the element in question.
        $(this).animate({"opacity":"1"}, "fast");
    });

    $('.thumb').on('click', function() {
        animate();
    });

    window.on('scroll', function() {
        if ($(this).scrollTop() > 20) {
            animate();
        } else{
            sbContainer.draggable();
        }
    });
    //You only need to make this draggable once, either here or in your else statement.
    //Remove one depending on what you need.
    sbContainer.draggable()

})(jQuery, window); //Here we set our awesome stuff in the function

UPDATE

I've looked at your .js file and there's quite a bit I would change. But focus on the resize event for now. The way you have it now, the code runs hundreds of times since it is called each time the window size changes, even if the user isn't done resizing.

Now we don't want to do that since it can really slow down the browser, if not crash it all together. So what you want to do is only run when the user stops or is done resizing, then run the code. Here's an example of how I'd probably do it:

var $window = $(window); //Remember, if you use a selection more than once, you should cache it.
$window.resize(function() {
    //Check if there has been a call already
    //If the check is true that means the code was already called
    //So we cancel any previous calls, this way the code is only called once
    if(this.resizeTO) clearTimeout(this.resizeTO);

    this.resizeTO = setTimeout(function() {
        $(this).trigger('resizeEnd'); //Call the actual code with a 500ms delay
    }, 500);
});

$window.on('resizeEnd', function() {
//This is a custom event that is triggered in the timeout
//This will only run on the last time the resize method was called
    var winWidth = $window.width();

    if( winWidth < 960 ) {
        toggletwo();
        animate();
    } else {
        toggleone();
    }
});


Compare last modification time with specfied time

I think you were actually on the right path. I really do not concur with the "represent dates with floats" approaches: they force you to add many comments that (1) describe in what units your variables are (seconds, microseconds, whatever) and (2) indicate the reference time (epoch time, etc.). Instead, I recommend to manipulate dates directly: (1) the code is readily understandable, and (2) this allows one to do simple prints of the variables and get obviously meaningful results (useful for debugging and maintaining the code, etc.).

Here is a simple implementation:

import os
from datetime import datetime, timedelta

file_mod_time = datetime.fromtimestamp(os.stat(file_name).st_mtime)  # This is a datetime.datetime object!
now = datetime.today()
max_delay = timedelta(minutes=args.time)

if now-file_mod_time > max_delay:
    print "CRITICAL: {} last modified on {}. Threshold set to {} minutes.".format(file_name, file_mod_time, max_delay.seconds/60)
else:
    print "OK. Command completed successfully {} minutes ago.".format((now-file_mod_time).seconds/60)

(This is not exactly what your original code does, but I'm not sure whether you really intended to use both a delay of 30 minutes and args.time, from the text of the question: I merged them. The code can be easily adapted to your case, were it slightly different.)

This is much more legible. There is also really no need to add many comments about what is being done, as everything is explicit (today(), timedelta(), .seconds,…). No need to do much calculations either, or to round things (int(), round()). You also get a neat date+time printing for free (the printed file_mod_time).

More generally, I would advise to always have variables be of the type of object that they represent. In your case, Python offers a nice date+time class, so I would not never suggest to downgrade dates and time intervals to pure numbers, as their meaning is not obvious (units? time corresponding to number 0?).


Find the thousandth integer without the digits 3, 4, and 7

import java.sql.Date;

You shouldn't need anything from java.sql unless you're using a relational database. java.util.Date would be more appropriate here (or nothing at all).

public class FirstChallange {

Challenge has one a and two es.

The name is not going to be very helpful in identifying the purpose of the class in six months' time, and there's no comment to say what the source of the challenge was either.

    private static int removedNumbers;
    private static int numberQuantity;
    private static int lastNumberFound;
    private static int cont;
    private static int pos3;
    private static int pos4;
    private static int pos7;

Variables should usually be in the narrowest scope possible. This means that static fields should be extremely rare.

        long inicio = System.currentTimeMillis();

It's best to be consistent in the use of language: either name all the variables in Portuguese or name them all in English.

This line has trailing whitespace. If you can configure your IDE to automatically remove this, you will reduce the number of spurious changes which muddle revision control diffs.

        DecimalFormat dfmt = new DecimalFormat("0");

        System.out.println(dfmt.format(lastNumberFound));

That is heavily overkill for System.out.println(lastNumberFound);

        removedNumbers = 0;
        numberQuantity = 10000000;

        for (cont = 1; removedNumbers <= numberQuantity; cont++) {
            String str = new String();
            str = String.valueOf(cont);

            pos3 = str.indexOf("3");
            pos4 = str.indexOf("4");
            pos7 = str.indexOf("7");

Actually iterating over objects is rarely the best way to count them. Iteration with filtering even less so. If you spend some time thinking through the mathematics before you start writing code, there's an easy way to tackle this problem by base conversion which takes about 20 milliseconds.