Some style notes (you can read more 'bout them on Python's official style-guide which is called PEP8):

you misspelled Caeser. It should be Caesar.
function names should be snake_cased not camelCased
instead of commenting lines at the middle of the method, just add a docstring:

def choose_mode():
    """
    Docstring here
    """
    # the rest of your code

you should add the if __name__ == '__main__' guard

About the code

It's pretty weird to use exit which is a helper for the interactive shell instead of sys.exit which is intended for use in programs. I'd  stick to the latter.
In collectMessage() you can directly return raw_input("Enter the message you would like to translate:\n\n")
In collectKey(): you can remove both continue statements
You should use format() when printing. Here, you can read more about formatting.

About the algorithm

In Python, we have the translate method which applies a substitution cipher to a string. More, when building the translation table, in Python 2, we have string.maketrans.

import string
from string import ascii_lowercase

shift = 6
cipher = string.maketrans(ascii_lowercase, ascii_lowercase[shift:] + ascii_lowercase[:shift])

print "I love to review code at midnight because I have no life".translate(cipher)

Which outputs:

  I rubk zu xkbokc iujk gz sojtomnz hkigayk I ngbk tu rolk

Another built-in that you may take advantage of is:

"I love to review code at midnight because I have no life".encode("rot13")

PS: You can also have a quick look at this answer for other recommendations that might apply quite well to your code.


first I suggest you use pointers to keep the mutex reference; this makes it possible to have a non-owning state when the pointer is 0 (the state when default initialized)

also you created a copy constructor and a destructor, so you still need a copy assignment to properly follow rule of 3 (or at least disable it)

GetLock<TLOCKABLE>& operator=(const GetLock<TLOCKABLE>& plock) {
    if(plock.lock != lock){
        GetLock<TLOCKABLE> tmp(plock);
        swap(tmp);

    }
    return *this;
}

however this keeps the assumption that the lock is recursively-lockable, but as an optimization it won't reacquire and release when the locks are the same


Range Minimum Query Implementation in Scala

For starters,
  your spacing is rather inconsistent: val j =0 val i=from,
  typos abound: storeElements, numberOfElements numberOfQueries,
  and you terminate some statements with ;.

Be aware that a lambda foo => bar(foo) is similar to the declaration def anonymous(foo) = bar(foo). That is, the parameter name foo is already declared by being a parameter – your val i = from is a absolutely unnecessary. Similarly,  val j = 0 is not needed because j <- ... in the for-comprehension already amounts to a declaration.

In Scala, curly braces {} and parens () are rather similar. Use curlies only when using a multi-statement lambda.

In one place, you do _.toInt, in another you Integer.parseInt(_). I'd rather use the first solution, as it is shorter.

If we clean up these minor problems (and remove some unnecessary variables), we end up with this code:

object Solution {
  def main(args: Array[String]) {
    val readInfo = readLine.split(" ")
    val numberOfElements = readInfo(0).toInt
    val numberOfQueries  = readInfo(1).toInt
    val storeElements = readLine.split(" ").map(_.toInt)
    for (i <- 0 until numberOfQueries) {
      val z = readLine.split(" ")
      val from = z(0).toInt
      val to   = z(1).toInt + 1
      val getNumber = (from until to).map(i => storeElements(i))
      println(getNumber.min)
    }
  }
}

A number of things appears suspect, for example the name z which should better be range, and the +1 for the upper bound of the range. The a until b method excludes the upper bound [a, b). However, there is also a a to b function, which produces an inclusive range [a, b].

The getNumber variable has a rather weird name, and I wouldn't even assign this value to a name. The minimum is more interesting than the slice.

What (z(0).toInt to z(1).toInt).map(i => storeElements(i)) calculates is a slice of elements in the array. There is the builtin method slice for this use case (which takes the inclusive lower and exclusive upper bound as arguments).

We now have the code:

object Solution {
  def main(args: Array[String]) {
    val problemSize = readLine.split(" ")
    val elements = problemSize(0).toInt
    val queries  = problemSize(1).toInt
    val input = readLine.split(" ").map(_.toInt)
    for (i <- 0 until queries) {
      val range = readLine.split(" ")
      val minimum = input.slice(range(0).toInt, range(1).toInt + 1).min
      println(minimum)
    }
  }
}

But is this a Range Minimum Query? No, it just returns the minimal element in that slice. We are not interested in the minimal value, but rather in the position of the minimal value.

Because this is just a code review, I won't explain an algorithm for performing the RMQ, but the external links in the Wikipedia article you linked to contain a few algorithms.


PHP Output Block Defining and Best Practices

The first problem i can see and many other's is that your hardcoding output data, why would you hard code output data on within a language that was built for dynamic content creation.

I would suggest that you restructure your class to combine several entites into one, for example, when creating a html web page, i usually is constructed of 5 major compoinants, for isntance:

Page

Head
Body

Header
Main
Footer

Taking this into consideration i would like to make my code so it would act in the same way, create 6 or so classes called:  HTMLPage, HTMLHead, HTMLBody, HTMLBodyHeader, HTMLBodyMain, HTMLBodyFooter

Now each class should be assigned to it's parent, for example:

The Head and Body belong to the Page, and the Header,Main and Fotter belong to the Body, this taken into consideration you should look at the following structure:

/*
 * Create a Page
*/
$Page = new Page("DOCTYPE");

/*
 *Create a Head
*/
$Head = new Head();
$Head->title = "My Practical Home Page";
$Head->addScript("http://google.com/example.js");
$Head->addStyle("http://google.com/example.css");
$Head->addMeta('blah','..blah..');

/*
 * Create a Body Object
*/
$Body = new Body("charset");
$Body->layout = new HTMLLayout("some_file_to_specifiy_the_layout");
$Body->SetContent('LeftBlock.Top','Hello World');

/*
 * Create Footer
*/
$Footer = new Footer('default_footer.php');

/*
 * Add all the segments to the main page!
*/
$Page->head = $Head;
$Page->body = $Body;
$Page->body->header = $Header;
$Page->body->main = "....";
$Page->body->footer= $Footer;

/*
 * Send the page to the browser!
*/
$Page->Display();

I will leave it down to you to figure out the classes


Storing disassembled data in a structured way

This is a superfluous use of a list comprehension: [instruction for instruction in dis._get_instructions_bytes(…)].  You can just call dis._get_instructions_bytes() directly.

As indicated by the _ prefix, dis._get_instructions_bytes() is an undocumented and unsupported method.  If you choose to write code that relies on undocumented behaviour, you have a duty to point it out with an obvious apologetic comment.

I'm not convinced that you need to use an undocumented function, though.  dis.get_instructions() seems to work just fine.

The use of next() to iterate through disassembled_raw is awkward, and I'm sure that is what prompted you to post this question.  Fundamentally, what you want to achieve is a "group by" operation, so you want to use itertools.groupby().  The only tricky thing is that you want instruction.starts_line being None to mean that that instruction should be lumped with the previous batch.  For that, you could use a hack: make the key function stateful.

You seem to have a stray print() call at the end, left over from debugging.

Suggested solution

import dis
import itertools

def pretty_dis(function):
    last_seen_starts_line = None
    def stateful_starts_line(instruction):
        """Extract line number for the instruction, which is either
           instruction.starts_line if there is one, or the previously
           seen instruction.starts_line if there isn't."""
        nonlocal last_seen_starts_line
        last_seen_starts_line = instruction.starts_line or last_seen_starts_line
        return last_seen_starts_line

    return {
        line_num: list(instructions)
        for line_num, instructions in itertools.groupby(
            dis.get_instructions(function), key=stateful_starts_line
        )
    }


One thing that immediately stands out to me is whether $_FILES['uploadfile'] actually exists for each upload request.  Do an isset on it first to make sure a client doesn't send a post with fabricated input values - for example: some custom html form of their own making.  If they do, you'll get 'function expects some value, boolean/null given' errors all over the place as is.

Or better yet, to allow client flexibility if they choose to use some sort of API for your website, just cycle through $_FILES array to work on whatever files they submit to this script.  Your choice though if you want to instead maintain strict input, but it wouldn't matter really as long as your script receives the file input of a field named "uploadfile" from any source.

Also, for $_FILES[$x]["name"], validate or sanitize it to ensure it contains only alphanumeric, underscore, dash, and dot characters.  Yes OS's can work with more characters than that, but not every protocol or application can (text, browsers or email editors breaking long filenames or links on spaces, etc).


Here's my take:

from random import randint
name = raw_input('Please Type in your name > ')

print """
Hello {} & welcome to the Random Number Generator by Ray Weiss.
""".format(name)
upper = int(raw_input('Enter the upper limit > '))
n = int(raw_input("How many D{} you'd like to roll? ".format(upper)))

for _ in xrange(n):
    print randint(1, upper)
print """
Thank you {} for using the D{} RNG by Ray Weiss! Goodbye!
""".format(name, upper)

Changes as compared to your version:

directly import randint because it's the only function you use in random;
use the new string formatting method (str.format);
take the upper bound from user instead of hard-coding 20;
take the number of rolls from user instead of repeatedly asking if that's enough;
use a loop to make the repetition actually work. The self-repeating code asking the user if we should continue is now gone.


There are a few things I can spot in your code that seem off to me.

Your code could realy do with some more comments. You put the comments on the lines that seem quite obvious to me, but when you start calculating the new position things get a little more complicated and you don't comment any more. I believe it should be the other way around.
Animating margins is not realy such a good idea when it comes to performance. You are much better of using the cheaper transform: translate3d() as I tried to explain here. It should make your animation a lot smoother.
There is a lot of repetition in your code, which is never a good idea. You set that 'margin-left' on 10 different lines for example. Why not first calculate it, and then set it just once? If you decide, for example, to work with transforms somewhere in the future, you would have to update all 10 of those lines, while it could be just a single line. And it would make your code a lot shorter, which is always nice.
There are a lot of nested ifs in there, which does not improve the readability of your code. I try to never nest ifs. If you really have to, you are probably doing something wrong. Most often you can avoid this by splitting your code into multiple functions (single responsibility), working with early returns or just rethinking your logic.
When you assign just a single variable in an if / else block, you are better of using the ternary operator. It is more compact (which is always good in js) and I think it makes your code better readable.

I went ahead and tried to refactor your code with those tips in mind (not the translate, I leave that up to you to decide). Note that this code is not tested (it's a bit hard with only part of your plugin) but I believe it should do the same as your code does. It is a bit shorter and a lot better readable imo.

slider.prototype.transition = function(position, offset) {
    this.position = position;
    this.offset = offset;

    // update new slide position if deeplinking
    this.slide_pos = parseInt(this.position) || this.slide_pos;

    //check slide no exists in dl_urls object
    this.deep_link_slide_no =
        window.hasOwnProperty(this.deep_link_slide_no)
        ? 0
        : position;

    // -- calculate new margin left
    var marginLeft = 0;
    // position == 0
    if (this.position === 0 || this.slide_pos === 0) {
        marginLeft =
            this.options.centered
            ? -(0.5 * this.slideWidth)
            : this.offset || 0;
    }
    // position != 0
    else {
        marginLeft =
            this.options.centered
            ? -(this.slide_pos * this.slideWidth) - (0.5 * this.slideWidth)
            : this.offset == 'undefined'
                ? (((this.slide_pos * this.slideWidth) * -1) + this.offset)
                : ((this.slide_pos * this.slideWidth * -1)) || (this.current_margin + this.direction);
    }

    // -- animate
    // transitions supported
    if (supportCSSTransitions && this.options.hardware_accelerated) {
        this.container.css({
            'margin-left': marginLeft,
            transition: 'margin 0.8s ease'
        });
    }
    // transitions not supported
    else {
        this.container.velocity({
            'margin-left': marginLeft,
        }, {
            duration: this.options.slide_delay,
            easing: this.options.easing
        });
    }

    this.current_margin = (this.current_margin + this.direction);
    this.set_button_state();
    this.set_active_states();
};


Shorter way of prompting for a height of x feet y inches?

The short answer is: Yes, there are ways to improve it!

Coding conventions

First of all, you are not following some Java coding conventions of indentation and where to put }-characters and similar.

Error messages

"Please try again" is not a message that really describes what went wrong. If I would see that message my first reaction would be to try to enter the exact same value again, which would just give me the same error message.

What your code does

Your code is essentially divided into two parts. The first part is:

    System.out.print("\nPlease enter your feet: ");
    int heightft = scanner.nextInt();

    if (heightft >= 2 && heightft <= 7) {
        System.out.println("You entered: " + heightft);
        Hresult = true;
    }
    else {
        System.out.println("Please try again");
        Hresult = false;
    }

Second part:

    System.out.print("Please enter your inches: ");
    int heightin = scanner.nextInt();

    if (heightin >= 0 && heightin <= 11) {
        System.out.println("You entered: " + heightin);
        Hresult = true;
    }
    else {
        System.out.println("Please try again");
        Hresult = false;
    }

Hresult in the first part of the code essentially has no effect because it will be overwritten by Hresult in the second part.

Now let's see what the common areas of this code are:

Show a message
Read an int from the Scanner
Check the range of the entered value
Show what you entered
Return whether or not the result was successful.

This could become it's own method.

public static int inputWithExpectedRange(String message, int min, int max) {
    do {
        System.out.print(message);
        int value = scanner.nextInt();

        if (value >= min && value <= max) {
            System.out.println("You entered: " + value);
        }
        else {
            System.out.println("Expected a value between " + min + " and " + max + ". Please try again");
        }
    }
    while (value < min || value > max);
    return value;
}

Now what you can do is to call this method twice from your previously existing method. It is also likely that you will find use for that method when the user should enter his/her weight.

System.out.println(); // this will print a line break *before* entering the input-method.
int feet = inputWithExpectedRange("Please enter your feet: ", 2, 7);
int inches = inputWithExpectedRange("Please enter your inches: ", 0, 11));
return feet * 12 + inches;

Violà.

An entirely different approach

As mentioned in the comments to your question, you can also use Regular Expressions to verify input and parse it. Here is a brief example of how to use Regular Expressions to input this. I will let you work on the details for it (such as making sure feet and inches are in the proper ranges). And you probably also want it inside some kind of loop (either while or do-while) to make sure that the user enters acceptable values.

    String input = scanner.nextLine();
    String regex = "(\\d+)'(\\d+)\"";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    if (!matcher.find()) {
        System.out.println("Input was not in normal feet and inch format");
    }
    int feet = Integer.parseInt(matcher.group(1));
    int inches = Integer.parseInt(matcher.group(2));

If you enter 5'11" the variable feet will be 5 and inches will be 11.


Avoiding Boundaries `if` Cases When Filtering Image Matrix

visiting black chess board squares

You might do a mod2 pre-calculation of mod(iRowIdx + iColIdx, 2) by creating a chess board boolean matrix before the loop, using matrix operations.

But much better would be to step iColIdx by 2. And have iRowIdx start at 1 or 2 as appropriate, and then step it by 2.

boundary checking

Your matrix now is C x R. Simply allocate a (C+2) x (R+2) matrix, so you have zeros running along all four sides. Then iterate over just the middle, rather than over the whole matrix as you are now. So iColIdx for example would start at 2 and stop one short of the end.

Doing this will delete a great many ifs, to give you Version2 of the code. You might even find that puts you in a position to produce Version3, which takes advantage of matrix operations instead of scalar operations, pushing much of the looping work down into matlab primitives, which would be faster.

style

It would have been helpful to see the method signature, but your English description that mOutputImage is the only return value worked well enough.

Typo: % Filteration

It would be natural to express the normalization e.g. like this:

    relWeight4 *= weightsNormalizationFactor;

Leave a blank after if, please.

The extra parentheses in mod and places like this:

        relPixel1 = mOutputImage((iRowIdx + 1), iColIdx);

are a little odd, you could safely elide them.


Adapting new design pattern with post handler

@GaryStorey hit on the simplest solution: Just pass your variables to the function:

// ...

likePost: function () {
    var $likePostEl = $(this),
        $postLikeCountEl = $likePostEl.children('#likeCount'),
        postLikeCount = $postLikeCountEl.data('count');

    var request = $.ajax({
        url: '/posts/like',
        data: {
            post_id: $likePostEl.parents().get(2).dataset.id,
            user_id: $likePostEl.parents().get(2).dataset.userid,
            like_count: postLikeCount,
            _token: token
        }
    });

    request.done(function (data) {
        Dnianas.Post.renderPostLike(data, $likePostEl);
    });
},

renderPostLike: function (data, $postEl) {
    var $likeCountEl = $postEl.children('#likeCount'),
        $likeIconEl = $postEl.children('.likeIcon');

    $postEl.toggleClass('liked', data.like);
    $likeIconEl.toggleClass('liked', data.like);
    $likeCountEl.text(data.like_count);
},

// ...

You'll note a few more changes:

There's no real need to pass all the variables. It seems everything can be found via the post element. So just find 'em.
Using .toggleClass() with a boolean as its 2nd argument is simpler than if/else branching
I've removed self for 2 reasons:

it's confusing that self isn't used to make a closure reference to this but to something else entirely
It's not that hard to just write Dnianas.Post. instead of self.

Looking at your code though, I suspect you have some flaky HTML and CSS too.

Why is it necessary to set the class liked on both the post element, and one of its children (the like icon)? Your CSS should just have a rule like post.liked .likeIcon { ... } so you only need to set the class on the post element, and the icon automatically changes.
The like-count element should probably not have that ID. Element IDs are meant to be unique across the whole page. I imagine you probably have several posts on a page, which would mean you have multiple elements with the ID #likeCount - and that's bad! You're doing the right thing with the like icon: It has a class name. And, contrary to IDs, class names are meant to be repeated.

Also, this stuff:

$likePostEl.parents().get(2).dataset.id

is just very, very fragile and opaque. You're getting the... um, the id property of the dataset of the great-grandparent of the post-like-widget element? That's pretty abstract. What is that element? I'm guessing it's the overall post container element, but it might be <body> or some random <div> used for layout. Are you sure the great-grandparent will always be the right element? What if the like-widget is wrapped in a different structure, and the great-grandparent is no longer what you expect it to be? And why does the great-grandparent have that data?

If I'm not mistaken, the two pieces of data you're fetching are the post author's ID, and the post's own ID. Those should rather be set on the like-button element itself, so it's where it's needed.

Or you should use a selector with .parents(), like .parents(".postContainer") or something. That would make the code a lot more understandable, and make the markup more flexible.

And why are you using dataset instead of jQuery's .data() which has better browser support and does the same thing? Edit: Oh, right, it's using .get() which returns a "naked" DOM element without the jQuery wrapper. The alternative would be ....eq(2).data("id"), since .eq() returns jQuery-wrapped elements.

But I'm also wondering why you're sending the like-count to the server. The server presumably knows the count, and is sure to be up-to-date unlike the page you're looking at. The server presumably also knows the user ID (whether it's the current user's ID, or the post author's ID). All you should need to send is the post's ID.


Optimize Performance challenge 'Vinay Queried '

Target string could be 5000 digits strong. It means that the target_subsets can have up to 12500000 elements. It is huge (I am surprised that the memory limit was not exceeded). You scan all of them for each query. Time limit exceeded obviously.

One obvious improvement is to sort target_subsets, and look for a lower bound of a query value (in logarithmic time). The result is simply len(target_subsets) - lower_bound.

This is still suboptimal, because the way you compute target_subsets has \$O(N^3)\$ time complexity. It is another candidate for TLE. It is more or less trivial to reduce it to \$(N^2)\$, but I'd still be uncomfortable.

The solution is a simple linear scan, along the lines of

Let `d` be a first non-zero digit of a query string
For target digit 't' at index 'i'
    if t > d, there are `len(target_string) - len(query) - i` pairs (as long as it is positive);
    if t == d, there _may_ produce one extra pair;
    it 0 < t < d, there are `len(target_string) - len(query) - i - 1` pairs (again, as long as it is positive);
    if t == 0, there are as many pairs as for the next non-zero digit.


Unit testing a click event with asynchronous content

Without the real code to be tested, I can only provide an example of how I've tested something similar with QUnit and Sinon.JS, though you don't even need the latter.

You can either use Sinon.JS to mock a response to the AJAX call or substitute your own manual mock for $.getJSON or $.ajax. I find the former preferable as it documents the AJAX call and tests the full front-end code, but it's beyond the scope of this question. You could argue that you're needlessly testing jQuery itself, and you'd be right. YMMV :)

Mocking JQuery

Let's assume this click event handler that uses the /load-foo AJAX call to acquire a JSON string. I've omitted the extra deferred for simplicity as your current test of the promise attached to the #foo element is fine.

$('#foo').on('click', function(){
    $.getJSON('/load-foo', {
        foo: 'bar'
    }).done(function (foo) {
        $('body').text(foo);
    });
});

Here's how you would test this handler.

test('foo text via AJAX set on body after clicking #foo', function(assert) {
    var $foo = $('#qunit-fixture').find('#foo'),
        getJSON = $.getJSON;

    $.getJSON = function (url, data) {
        assert.equal(url, '/load-foo');
        assert.equal(data.foo, 'bar');
        return new $.Deferred().resolve('"foobar"');
    }

    $foo.trigger('click');

    assert.equal($('body').text(), 'foobar');
    $.getJSON = getJSON;
});

For safety, I'd recommend saving and restoring $.getJSON in the module's setup and teardown functions. If you don't, any exception thrown in the test will leave the mock in place.

Mocking AJAX

While this does result in a lot of boilerplate sometimes, you can use Sinon's fake server to mock the AJAX responses. The beauty here is that it will match up the request to the response to ensure your AJAX calls (URL, data, type, etc.) are all correct and then supplies a canned response.

Here's the same test above using a fake server.

module('AJAX tests', {
    setup: function () {
        this.server = sinon.fakeServer.create();
    },
    teardown: function () {
        this.server.restore();
    }
});

test('foo text via AJAX set on body after clicking #foo', function(assert) {
    var $foo = $('#qunit-fixture').find('#foo');

    // setup the expected request with the canned response
    this.server.respondWith('/foo',
        [ 200, { 'Content-Type': 'text/json' }, '"foobar"' ]
    );

    $foo.trigger('click');

    // handle queued requests immediately
    this.server.respond();

    assert.equal($('body').text(), 'foobar');
});

If you're mocking a lot of JSON AJAX requests, you can create a common fixture to make this a little saner. You can call this.mockAjax with a number for an HTTP response code, an object to convert it to JSON, or a string as the raw response.

var ajaxFixture = {
    setup: function () {
        this.server = sinon.fakeServer.create();
    },
    teardown: function () {
        this.server.restore();
    },
    mockAjax: function (url, response) {
        var type = { 'Content-Type': 'text/json' };
        if (typeof response === 'number') {
            this.server.respondWith(url, [ response, type, '' ]);
        }
        else if (typeof response === 'object') {
            this.server.respondWith(url, [ 200, type, JSON.stringify(response) ]);
        }
        else {
            this.server.respondWith(url, [ 200, type, response ]);
        }
    }
);

Then you simply use this as the module's fixture:

module('AJAX tests', ajaxFixture);

test(...);

Non-Mocking Solution

As you say in your comment, you want to execute the full AJAX call to your backend service.

  Note: This is not unit testing anymore but rather functional or integration testing. Unit testing involves testing each small piece (unit) in isolation of the others: the click handler. Adding in jQuery, XMLHTTPRequest, and your backend service will make isolating bugs more difficult. But it is useful for making sure all the pieces work together.

  I still recommend doing actual unit tests in addition to integration testing for quicker development as they typically run much faster and can be executed with every change to a source/test file from your IDE.

First, modifying your click handler invalidates any test you run, so we'll need to leave that in place, i.e., no simulated call or extra deferred. Your best bet is to poll for the call to complete with an interval and fail the test if it doesn't complete within X seconds.

test('foo text via AJAX set on body after clicking #foo', function(assert) {
    var $foo = $('#qunit-fixture').find('#foo'),
        $body = $('body'),
        done = assert.async(),
        timeout = Date.now() + 5000, // timeout after 5s
        timer;

    $foo.trigger('click');

    timer = window.setInterval(function () {
        if ($body.text() === 'foobar') {
            assert.equal($body.text(), 'foobar');
            window.clearInterval(timer);
            done();
        }
        else if (Date.now() >= timeout) {
            assert.ok(false, 'AJAX timed out');
            window.clearInterval(timer);
            done();
        }
    }, 250);
});

Obviously, this won't work if you're using Sinon's fake timers, so disable them for this test if enabled globally. Also, you'll need to figure out if a slow AJAX call will interfere with later tests when it finally completes and puts "foobar" into the body. Maybe you want to put it into the fixture itself instead of polluting the global body.


Book repository for storing books that are accessed by ISBN

Your code is nice and the only advice I can give you is this: getAllBooks() may be improved from linear to constant time.

Consider

public boolean addBook(Book book) {
    Book copy = new Book(book);

    if (!books.containsKey(copy.getIsbn())) {
        this.list.add(book);
        return books.put(copy.getIsbn(), copy) == null;
    }

    return false;
}

public List<Book> getAllBooks() {
    return Collections.unmodifiableList(this.list);
}

Hope that helps.


Printing a pattern through the use of a dictionary

For how you're using it, it seems like a list of lists would make more sense than a dict. This is somewhat like a 2-dimensional array in C.

Your mtn initialization becomes:

mtn = []

You'll need to do a little more work in space_mtn to generate the sublists:

def space_mtn(height,mtn):
    for i in range(height):
        mtn.append([])             # Append an empty sublist at each level
        for j in range(2*height+2):
            mtn[-1].append(" ")    # Append a space to the end of the currently-last list
    return

Now in hash_mtn and print_mtn, just change your mtn[i,j] calls to mtn[i][j].

Now, there are lots of ways to make this code less C-like and more "Pythonic". Such discussions are probably better for Code Review. I'll just say that it's possible (although not necessarily "best") to get equivalent functionality by replacing everything after your input while loop with one line:

print('\n'.join('{0:>{1}}  {0:{1}}'.format('#'*(i+1), height) for i in range(height)))


Free a binary tree without using recursion or allocating memory

function missing templates

I'm sure you're aware, but the functions need the same templating as the Node such that void freeTree(Node* t) becomes:

template<typename T>
void freeTree(Node<T>* t)

slight reduction in memory use

You could slightly reduce the stack used by essentially inlining the function call to findBottomLeft.  The rewritten function now looks like this:

template<typename T>
void freeTree(Node<T>* t)
{
    // bl points at the bottom left node.
    // Any right nodes from t are added to the bottom left as we go down.
    // This progressively flattens the tree into a list as we go.
    Node<T> *bl;
    for(bl=t ; bl != nullptr && bl->left != nullptr; bl=bl->left);

    while(t != nullptr)
    {
        // body of for loop deliberately empty
        for (bl->left = t->right; bl != nullptr && bl->left != nullptr; bl=bl->left);
        Node<T>*   old = t;
        // Now just free the curent node
        t = t->left;
        delete old;
    }
}

Note that I'm using nullptr rather than NULL here which is a C++11 feature.  If you're not using a C++11 compliant compiler, you can simply use NULL for each of those instances.

Also, I've eliminated the early return in the case that t was equal to NULL in the original because this case is handled correctly by the for loop and while loop.

It's also important to realize that the body of the for loop is deliberately empty.  Some people dislike having a for loop with just a semicolon at the end, but I think it's not a problem if there is a comment pointing it out.


Explanation:

It's true that using objects can become messy after a while. That's why Template Literals and innerHTML are so powerful in this situation.

I would highly advise to avoid using parentNode when attempting to remove HTML, you may unintentionally remove something in the future if you decide to make your alert HTML more complex.

To solve this, create a container element that is accessible by your onclose method.

Also, I would also advise to not overwrite existing objects. Why not name alert to something else?

Don't add onclick events directly in the HTML, it's messy.

Solution:

function message(text) {

  const container = document.createElement("div");

  const onClose = ()=>container.remove();

  container.innerHTML = `

        close
        ${text}

  `;

  document.body.appendChild(container);

  document
    .querySelector('i#close-alert')
    .addEventListener("click", onClose);
}

Working Example:

function message(text) {

  const container = document.createElement("div");

  const onClose = ()=>container.remove();

  container.innerHTML = `

        close
        ${text}

  `;

  document.body.appendChild(container);

  document
    .querySelector('i#close-alert')
    .addEventListener("click", onClose);
}

const button = document.querySelector('button');
button.addEventListener('click', function() {
  message('Button clicked');
});
* {
  box-sizing: border-box;
}

.shadow {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .5);
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 98;
}

.alert-text {
  border: 1px solid #aaa;
  padding: 2.5em;
  min-height: 10%;
  width: auto;
  max-width: 80%;
  background: #fff;
  z-index: 99;
  position: relative;
  text-align: center;
}

.alert-text i {
  position: absolute;
  top: 0;
  right: 0;
  color: #777;
  cursor: pointer;
  padding: .5rem;
}

.alert-text i:hover {
  color: #444
}
<!DOCTYPE html>

  <title></title>

  <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Page content

  <button>alert</button>


Useless transformation

Since fgetcsv() returns an indexed array, the statement

$cols = array($row[0], $row[1], $row[2], $row[3]);

is totally useless: it results in $cols which is exactly the same as $row.

Using any number of columns

BTW, the above already answers part of your concern, regarding:

  its assuming a X number of columns

Directly working with $rows you keep all original columns.

The last part is that this statement:

echo '<div>'.$row[0].' | '.$row[1].' | '.$row[2].' | '.$row[3].' </div>';

can be replaced by:

echo '<div>' . implode(' | ', $row) . ' </div>';

Then, again, you'll get the exact content, whatever is the number of columns.

So your whole code can be reduced like this:

$ch = fopen("test.csv", "r");
$header_row = fgetcsv($ch);

/* This will loop through all the rows until it reaches the end */
while($row = fgetcsv($ch)) {
    if (in_array("text", $row)) {
        echo '<div>' . implode(' | ', $row) . ' </div>';
    }
}

NOTE: if (in_array("text", $cols)) is enough and you don't need to look for FALSE, since fgetcsv() doesn't return falsy value other than FALSE itself.

Any not empty content is obviously not FALSE, and an empty line returns [0 => null], as stated by the manual:

  A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

Using regexes

There is no need to use regexes: you're looking for a unique precise value, so in your case it'll be overkill!

It might not be the same if, for example, you wanted to find "text" even if it's only part of one (or more) column content.

Then you should do something like this:

if (preg_match('/text/', implode('', $row)))

Here we had to turn $row content into a string before applying the pattern.
But this can be improved in the context of your snippet: do implode() only once, so it will be alredy done for the echo, while the additional | doesn't matter for the preg_match.

This way, it'll result in:

while($row = fgetcsv($ch)) {
    if (preg_match('/text/', $row = implode(' | ', $row))) {
        echo '<div>' . $row . ' </div>';
    }
}


Your code doesn't really work when used by humans. The first thing I did was run the code and type in a time, which failed. When a human enters data through the terminal, they will hit Enter, which is returned from read_line:

$ echo '07:05:45PM' | cargo run
input error: expected 10 characters, got 11
$ echo -n '07:05:45PM' | cargo run
19:05:45

Style issues - learn to love rustfmt:

There's no space before : when specifiying a type on a variable.
Use trailing commas.
Match arms longer than one line should use curly braces {}

Accept a &str instead of String; the function doesn't need to take ownership of the string.
There's no need for the turbofish (::<>) on the parse calls; type inference handles that just fine.
Become very familiar with all the methods on Option and Result and Iterator. These are the bread and butter of idiomatic, concise, and performant Rust code. Specifically, if you match on a Result and have a match arm for Ok and Err, it's likely you want to use Result::map.
Avoid iterating through the characters from the beginning multiple times, it is less efficient than needs to be. Instead, use the same iterator multiple times through Iterator::by_ref.
I'd use expect in your main method, instead of matching and printing. There is a difference between the two, expect will cause a panic on Err, but that seems reasonable in main.
I never use unwrap, instead preferring at least expect; this helps find the line when the code finally fails.
Library code should very rarely panic; they should report errors. Especially report errors when it's because of input supplied to the code, panic for internal logic errors.
The match in read_12h_time can be flattened; you can pattern match against Ok(10) directly.
stdin doesn't need to be explicitly locked; read_line will lock it.

use std::io::{stdin, Error, ErrorKind, Result};

struct Time {
    hour: u8,
    minute: u8,
    second: u8,
}

impl Time {
    pub fn from_12h(time: &str) -> Result<Time> {
        assert!(time.chars().count() == 10);
        let mut chars = time.chars();

        let hour: String = chars.by_ref().take(2).collect();
        let minute: String = chars.by_ref().skip(1).take(2).collect();
        let second: String = chars.by_ref().skip(1).take(2).collect();
        let period: String = chars.by_ref().take(2).collect();

        Time::hour_from_12h_to_24h(hour.parse().unwrap(), &period).map(|hour_24h| {
            Time {
                hour: hour_24h,
                minute: minute.parse().unwrap(),
                second: second.parse().unwrap(),
            }
        })
    }

    fn hour_from_12h_to_24h(hour: u8, period: &str) -> Result<u8> {
        match period {
            "AM" => Ok(hour % 12),
            "PM" => Ok(hour % 12 + 12),
            _ => Err(Error::new(ErrorKind::InvalidData, format!("invalid period {}", period))),
        }
    }

    pub fn to_24h(&self) -> String {
        format!("{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
    }
}

fn main() {
    let time_12h = read_12h_time().expect("input error");
    let time = Time::from_12h(&time_12h).expect("error");

    println!("{}", time.to_24h());
}

fn read_12h_time() -> Result<String> {
    let mut buffer = String::new();
    match read_line(&mut buffer) {
        Ok(10) => Ok(buffer),
        Ok(length) => {
            Err(Error::new(ErrorKind::InvalidInput,
                           format!("expected 10 characters, got {}", length)))
        }
        Err(e) => Err(e),
    }
}

fn read_line(buffer: &mut String) -> Result<usize> {
    stdin().read_line(buffer)
}

On to bigger issues:

I don't like that the AM/PM matching and hour conversion are tangled together.

Instead, introduce an enumeration to handle the AM/PM.

It feels like 12 hour time is a different type from 24 time.

Rename existing type to something unique.
Store the new AM/PM enumeration.
Introduce new type and add conversion methods.

I don't like reusing io::Error for your own errors.

Introduce a custom error type. I like to use quick_error, but there are other solutions.

I don't like that IO is embedded inside of the logic of the library.

Separate IO and parsing logic and only combine them at a higher level - in this case main.
Push time-specific logic (e.g. 10 character checks) back into the library. Note that this removes the duplication of the logic in the assert and removes a panic inside the library.

The code doesn't fully participate in the Rust ecosystem.

Implement traits like FromStr and From and Display (perf!).
Derive standard traits to make it easier to use your types: #[derive(Debug, Copy, Clone, PartialEq)] is a good set.

There are too many panics inside the library portion.

Fully utilize Result and try! or the try operator ?.

There's too much unneeded allocation.

Instead of using characters and collecting them back to strings, operate on the incoming string and take slices instead.
Formatting can write directly into a formatter; there's no reason to allocate a string to just turn around and print it.

#[macro_use]
extern crate quick_error;

use std::str::FromStr;
use std::io::stdin;
use std::fmt;

quick_error! {
    #[derive(Debug, Clone, PartialEq)]
    enum Error {
        MissingMeridian {
            description("missing the meridian")
            display("Missing the meridian")
        }
        InvalidMeridian(what: String) {
            description("invalid meridian")
            display("Invalid meridian: {}", what)
        }
        MissingComponent(which: TimeComponent) {
            description("missing a time component")
            display("Missing {}", which)
        }
        InvalidComponent(which: TimeComponent, why: std::num::ParseIntError) {
            description("invalid time component")
            display("Invalid {}: {}", which, why)
            cause(why)
        }
    }
}

type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Copy, Clone, PartialEq)]
enum Meridian {
    AnteMeridian,
    PostMeridian,
}

#[derive(Debug, Copy, Clone, PartialEq)]
enum TimeComponent {
    Hour,
    Minutes,
    Seconds,
}

impl fmt::Display for TimeComponent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use TimeComponent::*;

        let name = match *self {
            Hour => "hour",
            Minutes => "minutes",
            Seconds => "seconds",
        };
        write!(f, "{}", name)
    }
}

impl FromStr for Meridian {
    type Err = Error;

    fn from_str(s: &str) -> Result<Meridian> {
        match s {
            "AM" => Ok(Meridian::AnteMeridian),
            "PM" => Ok(Meridian::PostMeridian),
            _ => Err(Error::InvalidMeridian(s.to_string())),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
struct TwelveHourTime {
    hour: u8,
    minutes: u8,
    seconds: u8,
    meridian: Meridian,
}

impl FromStr for TwelveHourTime {
    type Err = Error;

    fn from_str(time: &str) -> Result<TwelveHourTime> {
        use Error::*;
        use TimeComponent::*;

        let mut parts = time.splitn(3, ":");

        let hour = parts.next().ok_or(MissingComponent(Hour))?;
        let minutes = parts.next().ok_or(MissingComponent(Minutes))?;
        let seconds_meridian = parts.next().ok_or(MissingComponent(Seconds))?;

        if seconds_meridian.len() < 4 {
            return Err(MissingMeridian);
        }

        let (seconds, meridian) = seconds_meridian.split_at(2);

        let hour = hour.parse().map_err(|e| InvalidComponent(Hour, e))?;
        let minutes = minutes.parse().map_err(|e| InvalidComponent(Minutes, e))?;
        let seconds = seconds.parse().map_err(|e| InvalidComponent(Seconds, e))?;
        let meridian = meridian.parse()?;

        Ok(TwelveHourTime {
            hour: hour,
            minutes: minutes,
            seconds: seconds,
            meridian: meridian,
        })
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
struct TwentyFourHourTime {
    hour: u8,
    minutes: u8,
    seconds: u8,
}

impl From<TwelveHourTime> for TwentyFourHourTime {
    fn from(other: TwelveHourTime) -> Self {
        let hour = match other.meridian {
            Meridian::AnteMeridian => other.hour,
            Meridian::PostMeridian => other.hour + 12,
        };

        TwentyFourHourTime {
            hour: hour,
            minutes: other.minutes,
            seconds: other.seconds,
        }
    }
}

impl fmt::Display for TwentyFourHourTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:02}:{:02}:{:02}", self.hour, self.minutes, self.seconds)
    }
}

fn main() {
    let mut time = String::new();
    stdin().read_line(&mut time).expect("Unable to read input");

    let time: TwelveHourTime = time.trim().parse().expect("Unable to parse time");
    let time: TwentyFourHourTime = time.into();

    println!("{}", time);
}

  The problem is very simple, but the code seems too lengthy?

I don't suppose I made the length any better! However, I feel that the final code is pretty efficient, and when you start taking error cases into account, I would disagree that the problem is inherently "simple". Parsing text is complicated. You can use tools like regular expressions or parser combinators / generators, but those are just abstractions - the complexity is just hidden from view.

There's still logical aspects here that are strange. For example, the original code does hours % 12, which seems wrong, and my modified code does not, which also seems wrong! It's probably better to throw an error for invalid hourly values.


Your questions seem to have been answered (use jQuery), so here are a couple of small points regarding readability:

be consistent with your variable names (eg sliderImg vs flickrImgs: one is plural, one singular, and in the rest of the code, you mainly use flickrX, except for the sliderImg one; I would prefer sliderX everywhere, because it doesn't seem to matter where the images come from).
some variable names could be a lot better. Eg when reading flickrImgs/sliderImg I'm thinking it's an array of images (or image paths/names). But they are not, they are integers, so I would prefer imageCount/imageSize, and currentSliderPosition. flickrDisplay on the other hand seems to actually be a collection of images, so sliderImages would probably be a good name for it.
your indentation is off, which decreases the readability of your code.
your comments aren't all that helpful. NOW AND NEXT FUNCTION/SLIDE TRANSITION aren't really necessary, and For each loop incrementing each slide by one doesn't really help either (because that's exactly what the code already told me; If you do want to add a comment, it would be more helpful to explain what it means when a slide is increased.
use curly brackets even for one line statements to increase readability and to possibly avoid bugs.
visiable isn't a valid value for visibility, you probably meant visible.


Array partition 1 to group the array into pairs and make sum of minimum of pairs as maximum

Your logic is correct. You need each pair to include numbers as close as possible together, so that when you sacrifice each big number in the pair, the little number that survives is as large as possible while still being small enough to be shielded by the big number. The obvious way to pair up numbers like that is to sort them, and for the problem you've describe the language library sorting algorithm is probably the best choice.

There are still a few things that want cleaning up with this solution.

First, you are mutating your input array by sorting it. That is probably an undesirable side effect for this function, and should be avoided.

Second, it is often worth checking promised preconditions that you're relying on are actually honoured by whoever is using the function. This is where exceptions are useful. For example, I would check that the length of the input array is even.

Third, it is generally undesirable to use the import something.* form because it leads to confusion about where things are coming from.

Following the link, there is a further guarantee that

  n is a positive integer, which is in the range of [1, 10000]. All the
  integers in the array will be in the range of [-10000, 10000].

An array of size 20000 is plausible to hold in memory. This means that Counting sort is a plausible alternative to the sort from the Language library, and it has time complexity linear in the range of possible values, whereas the quicksort implementation used by Java is loglinear in the number of elements. (You don't have to unpack the count bins back into a sorted array, but can directly work out the pairs and smaller of the pairs)

In practice for the input constraints given I would still expect the quicksort to be faster and all round cheaper. However, I don't have any profiling on that; it's just a guess. Further, if the range of possible integers was very much smaller or the value of n was very much larger, implementing a counting approach would probably work well.

(Strictly speaking because, as above, you'd need to copy the input array to avoid mutating your input with a sort, given n is larger than the range of the values, an array of counts would be cheaper in terms of space too!)


1 Use Logger, do not print all your app info, in production it will mess up server logs. You can use different log level (debug, info). For example use info level in prod, and debug level in dev environment.

2  Do no catch all exceptions in service layers, you can throw them up to controller (if you use spring mvc) and catch all that there.

https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

3 Try keep your code clean to read and unsderstand.

public void sendMessage(String mobile, String Message) {
        ClickatellRest click = new ClickatellRest(APIKEY);
        ClickatellRest.Message response = click.sendMessage(mobile, Message);
        log.debug(response);
        if (response.error == null) {
            ClickatellRest.Message msg = click.getMessageStatus(response.message_id);
            log.debug(msg);
            ClickatellRest.Message msgStatus = click.stopMessage(response.message_id);
            log.debug(msgStatus);
        } else {
            log.error(response.err);
        }
    }

4 If you can, override toString() method in ClickatellRest.Message class if you often log this object.


Implementing two stacks using single array in java

I would go for

interface Stack {
    boolean isEmpty();
    int pop();
    void push(int x);
}

And then make a class providing two Stacks.

Also create a counter to detect when both stacks are full. This can be done with an AtomicInteger (thread-safeness) counting the free array slots.

public class StackPair {
    public final Stack firstStack = new Stack { ... };
    public final Stack secondStack = new Stack { ... };
    public StackPair(int capacity) { ... }

In StackPair the single array and an AtomicInteger freeEntries. In both Stack implementations access to the array and freeEntries.


It looks like you need to abstract out how you get the element that contains the test cases and then how you determine errors from the nodes in the element.

for test in self.parsed_report_file["suites"]["tests"]:

and

for xml_testcase in xml_testsuite.iter('testcase'):

get you the parent element to start the loop and then you need to determine whether the items are in error. I think it would make things easier if you did some of the refinement when you get the initial set of elements rather than doing more filtering in the loops. Since in the JSON case you only care about nodes matching test["name"] == test_case_steps[i]['step']['raw'] and test["state"], do that filtering when you grab the parent. Same for the XML, can you use XPath or similar to filter down to xml_testcase.attrib["name"] == test_case_steps[i]['step']['raw'] and "hook" not in xml_testcase.attrib["name"] before you start?

Once you have all that, the Jira-specific handling of errors (self.jira_obj.send_put) can be abstracted out to its own function that accepts the id, test step id and result object.


First part

You want to iterate through all possible combinations of for a pair of booleans, so you can make the code reflect that explicitly and make it simpler:

    System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");

    for (boolean p : new boolean[] {true, false}) {
        for (boolean q : new boolean[] {true, false}) {
            System.out.print(p + "\t" + q + "\t" + (p&&q) + "\t");
            System.out.println((p||q)+"\t"+(p^q)+"\t"+(!p));
        }
    }
    System.out.println();

Second part

You have something suspicious in your if statements. As you don't use braces, this code smells of a copy&paste bug:

    if(a==0 && b == 0 )
        not = 1;
        System.out.println(a + "\t" + b + "\t" + and + "\t" + or + "\t" + xor + "\t" + (not));

If the condition is met, it will execute the line not = 1;. The second line will be executed independently of the condition. I strongly suggest you use braces even for 1-line blocks, like this:

    if (a == 0 && b == 0) {
        not = 1;
        System.out.println(a + "\t" + b + "\t" + and + "\t" + or + "\t" + xor + "\t" + (not));
    }

This way you can avoid this kind of bugs.

Now, applying the same reasoning as with the previous method, you can rewrite it as:

    System.out.println("A\tB\tAND\tOR\tXOR\tNOT");
    for (int a : new int[] {0, 1}) {
        for (int b : new int[] {0, 1} ) {
            System.out.println(a + "\t" + b + "\t" + (a & b) + "\t" + (a | b) + "\t" + (a ^ b) + "\t" + ~a);
        }
    }

BUT What do you want to accomplish with the NOT operation? Do you mean the Bitwise Complement? I used that, but maybe you want a function that returns 0 when it's 1, and 1 when it's 0. In that case, you need to replace the ~a with something like (a == 0) ? 1 : 0.

So the whole code could be reduced to just:

public static void printTable() {
    System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");
    for (boolean p : new boolean[]{true, false}) {
        for (boolean q : new boolean[]{true, false}) {
            System.out.print(p + "\t" + q + "\t" + (p&&q) + "\t");
            System.out.println((p||q)+"\t"+(p^q)+"\t"+(!p));
          }
    }
    System.out.println();
    System.out.println("A\tB\tAND\tOR\tXOR\tNOT");
    for (int a : new int[]{ 0, 1}) {
        for (int b : new int[]{0, 1} ) {
            System.out.println(a + "\t" + b + "\t" + (a & b) + "\t" + (a | b) + "\t" + (a ^ b) + "\t" + ~a);
        }
    }
}


Your extension check is pretty much useless, as I can still upload a variety of files with extensions that can gain me code execution, such as php4 or .htaccess. If possible, use a whitelist approach instead.

But in your case, it doesn't really matter, as you are not using the extension anyways, the filename is just a random 5 character string without extension.

You should also always use prepared statements. Yes, $file is currently controlled by you, but who knows, that may change in the future.

Apart from this, I don't see any vulnerabilities in your script. My guess is that the vulnerability is somewhere else (seeing the logged request that you suspect would still be interesting).


SMB Script which collect remote files, mount locations, unmount locations, and show directory file tree

I didn't try to run your program. So some things may not work.

Imports. There is no need to do them twice like what you did with os and shutil. Just write import os or import shutil and then use them like os.walk and shutil.copy2. Same goes for glob.
PEP 8.

  Surround top-level function and class definitions with two blank
  lines.

  Limit all lines to a maximum of 79 characters. For flowing long blocks
  of text with fewer structural restrictions (docstrings or comments),
  the line length should be limited to 72 characters.

  Function names should be lowercase, with words separated by
  underscores as necessary to improve readability.

  Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

Docstrings should be surrounded by """. In selectSingleFile you used '''.

Naming conventions. Variables should have self-explanatory names. Your a, b, f don't say anything. getFileContents probably should be called something like get_files_list or get_dir_contents?
Type hints. With type hints you can help other people and yourself to understand what type of data your functions get as input and what type of output is going to be produced. For example, signature of your getFileContents will look like this:

def getFileContents(directory: str) -> List[str]:
    # Your code...

Don't forget to include from typing import List in the beginning.
You have not used variables called retcode. You can safely delete them. Also listDirectory is never used.
Some of your docstrings say for example: "Used to print...". Why not just write "Prints..."?
Instead of using subprocess.call you could use subprocess.check_call. So if something goes wrong you will get a CalledProcessError instead of nothing.
Your mount and unmount are quite similar. We could use partials. (I hope I didn't go too far with this). For example:

import subprocess
from functools import partial

def check_call(*args) -> None:
    subprocess.check_call(args)

mount = partial(check_call,
                '/sbin/mount',
                '-t',
                'smbfs')
mount.__doc__ = ('Mounts a remote directory '
                 'and chooses a local file '
                 'in which to mount the directory against')

unmount = partial(check_call,
                  '/sbin/umount')
unmount.__doc__ = 'Unmounts the local SMB directory'

Probably, something should be done about hard-coded call arguments but I'm not sure what.
In getFileContents instead of creating an empty list and then filling it we could create it by list comprehension. I propose two versions:

def getFileContents(directory: str) -> List[str]:
    return [file
            for *_, files_list in os.walk(directory)
            for file in files_list]

Note the *_. We use _ for throwaway variables. And with the asterisk we say that there are multiple throwaway variables like in your case: dirpath and dirnames.
Another way is to use itertools.chain:

def getFileContents(directory: str) -> List[str]:
    files_lists = [files_list
                   for *_, files_list in os.walk(directory)]
    return list(itertools.chain(*files_lists))

In selectSingleFile it would be good to add checking input. Take a look at the first answer here.
In the same function you calculate list of files twice. First, in the function itself and the second is in the printChoices. So, instead of passing local_dir to printChoices, pass already calculated list of files (a - how you call it)
Instead of joining paths with a + use os.path.join
By this point your function should look like this:

def select_single_file(local_dir: str,
                       destination: str) -> None:
    """
    Gets the contents of a directory
    and selects a single file to copy to a destination.
    """
    files = get_file_contents(local_dir)
    print_choices(files)

    # TODO: add checking
    file_index = int(input("Please select your choice: "))
    file_path = os.path.join(local_dir,
                             files[file_index - 1])
    shutil.copy2(file_path,
                 destination)

Finally, you have a counter variable in printChoices. Why not use enumerate? So, you will have:

def print_choices(files: List[str]) -> None:
    """Prints a numbered list of files in a directory"""
    for index, filename in enumerate(files, start=1):
        print(str(index) + ".", filename)

P.S.: "Please select your choice: " This is tautology.

Edit: You asked if it would be a good idea to expand functions to deal with exceptions. If you want to ask user to enter paths until he gives you correct ones then yes. But if you just want to throw an error if the entered path by user is incorrect, you should test your functions with valid and invalid input data. If for invalid input data you get a traceback from which it is not clear what goes wrong, you could add catching exceptions in those functions. I think you will need to use something from os.path.isfile, os.path.isdir, os.path.ismount and os.path.exists. Check the docs.


Flambino has already pointed out the issues in your code, so I'll just show how to tackle the problem with a different approach. A declarative and functional code (as opposed to imperative) favours immutability and known abstractions over manual control flow and in-place updates. Uusing lazy from Ruby 2 and String#present? from active_support (so we can write the more declarative code we can) it would look like this:

require 'active_support/core_ext/string'
sorted_words = $stdin.lines.lazy.map(&:strip).take_while(&:present?).sort
puts("Your list in alphabetical order is: #{sorted_words.join(', ')}.")


This line isn't needed in Python 3:

# -*- coding: utf-8 -*-

so you should probably just remove it. UTF-8 is assumed.

Your docstring is indented - why? It's not technically wrong, but it seem like a really arbitrary choice.

I'm not sure how to say this, but none of your sentences are capitalized. If this were a professional code-base, I would absolutely require good grammar and care of documentation. It is, after all, the primary text that represents the code.

I see _thread - you should be using the main threading interface. In particular, use threading.Lock instead of _thread.allocate_lock.

Since you're using Python 3, don't inherit from object - it's a no-op.

You have Logger.get_instance() return an instance of a different class. By this point, one should probably just make a get_logger function instead. Since that's not ideal, perhaps just overload __new__. You can do this with a metaclass, but a decorator is much simpler:

import threading
from functools import wraps

def singleton_new(make_instance):
    lock = threading.Lock()
    instance = None

    @wraps(make_instance)
    def __new__(cls):
        nonlocal instance

        if instance is None:
            with lock:
                if instance is None:
                    instance = make_instance(cls)

        return instance

    return __new__

This is as simple to use as

class Logger:
    @singleton_new
    def __new__(cls):
        return super().__new__(cls)

    def log(self, text):
        print(text)

and doesn't even affect the class' attributes, due to the magic of closures. One could use a class decorator instead, but I think this looks nicest. Note that this also allows usage on classmethods like

@classmethod
@singleton_new
def get_instance(cls):
    return super().__new__(cls)

Past that, I advise you to stick to PEP 8 where you can, which primarily means minor changes for your code.

On a design level, I strongly suggest rethinking using singletons at all. Globals are almost always better in such cases, and for the case of logging singletons aren't apropriate anyway (look instead at neat things like Logbook).

Even if you do conclude, for some reason, that you want singletons, at least consider the Borg pattern instead, which is mildly less aggrivating.


Little cleaner:

// Common Keys between left and right
var result = lChildren.Where(s => rChildren.Select(p => getKey(p)).Contains(getKey(s))).ToList();

// new keys added to right
result.AddRange(rChildren.Where(s => lChildren.Select(p => getKey(p)).Contains(getKey(s)) == false));

return result;

Without ToList():

public static IEnumerable<T> Merge<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
    foreach (var item in first)
        yield return item;

    foreach (var item in second)
        yield return item;
}

In your NodeMerge method:

return lChildren.Where(s => rChildren.Select(p => getKey(p)).Contains(getKey(s))).Merge(rChildren.Where(s => lChildren.Select(p => getKey(p)).Contains(getKey(s)) == false));


Brainfuck interpreter in JavaScript, take 2

I think I said I'd refrain from reviewing, since I reviewed the first take, but I can't help myself.

Again: I like it! It's very neat and tidy. I really can't fault it.

It's well-formatted
It's readable
It's efficient

Hell, it even taught me Brainfuck! Kudos!

If I were to be super nit-picky (and I'll have to be, to find something to write), it's that it'd be nice to use plural form for loop and operation (i.e. loops and operations). I know, I know, loops will ruin the nice 4-letter-aligned formatting that going on, but still.

next should perhaps be called current or similar, since that's what it actually is.

I guess you could skip the split(''), and just loop through the string, but either way works.

I might also prefer a stricter typeof brainfuck.end === 'function' check at the, uh, end, but that's just me being pedantic. OTOH, you could just stub it to a no-op function, and not have a check.

It might be nice to initialize data to [0], and have < and > initialize blank cells instead of doing it lazily in the +/- operations. It'd be a little more correct, and you'd avoid a program like . spitting out undefined instead of 0. You can do it in one (admittedly tricky) assignment:

'>': function () { data[++cell] = data[cell] || 0; }

Lastly, it might be nice to check input from read, since you could basically return whatever you want from your own read function. Worth it? Nah, not really.

I do have some other ideas, though. Less review, and more "what if...".

findJumps (formerly findLoops)

We talked about doing syntax-checking in the comments (and you came up with a nice implementation), so I'll skip that here. Instead, this is just an alternative to the code in the question.

function findJumps(code) {
  var jumps = [],
      stack = [],
      character, i, j;

  for(i = 0 ; character = code[i] ; i++) {
    if(character === '[') {
      stack.push(i);
    } else if(character === ']') {
      j = stack.pop();
      jumps[i] = j;
      jumps[j] = i;
    }
  }

  return jumps;
}

Instead of returning an array of objects, it's enough to just return an array of indices. It doesn't really matter what's start and end.

You could then change the [ and ] instructions to

'[': function () { data[cell] || (next = jumps[next]); },
']': function () { data[cell] && (next = jumps[next]); }

which seems nicely "symmetrical" :)

switch

Yeah, yeah, using a switch statement is boring. Still, it has some (minor) maybe-benefits:

Illegal characters can be absorbed by the default: case (or no case at all) - no need to sanitize the code string first (though depending on how loop-heavy the code is, it may be more efficient to sanitize it anyway).
It avoids declaring new operation functions on each call to run, and the calling overhead of those functions (though the impact of those things is in all likelihood zero; it's all optimized away).

Looks ok, I think (works too)

function run(code) {
  var jumps = findJumps(code),
      data = [],
      cell = 0,
      instruction, curr;

  for(curr = 0 ; instruction = code[curr] ; curr++) {
    switch(instruction) {
      case '>': ++cell;                              break;
      case '<': --cell;                              break;
      case '+': data[cell] = (data[cell] || 0) + 1;  break;
      case '-': data[cell] = (data[cell] || 0) - 1;  break;
      case '[': data[cell] || (curr = jumps[curr]);  break;
      case ']': data[cell] && (curr = jumps[curr]);  break;
      case ',': data[cell] = this.read();            break;
      case '.': this.write(data[cell]);              break;
    }
  }

  this.end();
}

The above assumes that this.end is (at least) stubbed. I've left out the cell initialization, but it works fine with that too.

Anyway, this is just me having some fun with it. Again, I can't really fault your code.

Now, how about tackling Befunge? Or maybe just Huh?


Since your actual machines are being handled by the Cloudflare based forwarding, you can let them handle the enforced SSL and www-prefixing rules instead.

However, if you do plan on the FULL SSL feature of cloudflare, you can combine the 2 separate rules into a single one:

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Notice that I do not rely on the $1 part of the URI, as matching (and capturing) that is just redundant.

Similarly, the next 2 rules can be combined:

RewriteRule ^/?(do|find)$ /$1.php [L]

You can chose to leave it as $1.php, but I prefer giving paths from the doc-root in my rules. It is just a personal preference.

Lastly, consider providing some gap between the Options directive and the directives provided by mod-rewrite. Again, it is another personal habit of mine; but makes it clearer to maintain large rule sets later on.


This is an ideal case for bisect/binary search.
Provided you did the right thing and the caption array is sorted by time.

Additional optimization for sequential playback is to check the adjacent captions' time before bisect. Sometimes we might want to rewind a couple of seconds back so let's cache the previous caption as well.

// sequential playback uses the adjacent caption to avoid array enumeration
this.captionState = {prevStart:-1, start:-1, end:-1, nextEnd:-1};

this.onUpdateTime = function(currentTime, totalTime) {
    var state = this.captionState;
    if (currentTime >= state.prevStart && currentTime <= state.start) {
        return showCaption(state.index - 1);
    }
    if (currentTime >= state.end && currentTime <= state.nextEnd) {
        return showCaption(state.index + 1);
    }
    if (currentTime >= state.start && currentTime <= state.end) {
        return false;
    }

    // bisect the caption array sorted by time
    var a = 0, b = $scope.chapters.length - 1;
    while (a < b - 1) {
        var c = (a + b) / 2 |0;
        if ($scope.chapters[c].time > currentTime) {
            b = c;
        } else {
            a = c;
        }
    }

    // find a caption that starts before currentTime amidst [b], [b-1], [b-2]
    // or hide the current caption if none found e.g. the first one doesn't start at 0
    for (var i = 0; i <= 2; i++) {
        if (b - i < 0 || currentTime >= $scope.chapters[b - i].time) {
            return showCaption(b - i);
        }
    }

    function showCaption(index) {
        var current = $scope.chapters[index];
        if (!current) {
            $rootScope.caption = '';
            $scope.$apply();
            return false;
        }
        $rootScope.caption = current.caption;
        $scope.$apply();

        var prev = $scope.chapters[index - 1];
        var next = $scope.chapters[index + 1];
        var next2nd = $scope.chapters[index + 2];

        state.index = index;
        state.prevStart = prev ? prev.time : -1;
        state.start = current.time;
        state.end = next ? next.time : totalTime;
        state.nextEnd = next2nd ? next2nd.time : totalTime;
        return true;
    }
};


GET multiple data frames using external module's function that uses requests

Your docstrings look a bit weird to me. The first line is usually a summary of what the function does. In your first function that line comes after the parameters and in the second one it does not exist at all. In get_stats when describing the parameter symbols there is no need to describe what the function internally does with it (i.e. split it up). This is an implementation detail (if it mutated the original list that might be worth mentioning but you don't do that).
I would put the chunking line into its own function, so you could change it if you want to at some time:

def chunks(it, n):
    """Splits `it` into chunks of length `n` (last chunk might be smaller)."""
   return [it[i : i + n] for i in range(0, len(it), n)]

The processing part is unnecessarily long. You could just write:

def get_stats(symbols):
    """
    :param symbols: List of symbols (can only send 100 at a time,
    so these may need to be broken up)
    :return: Pandas DataFrame with stats
    """
    with Pool() as pool:
        return pd.concat(pool.starmap(iex_get_stat, chunks(symbols, 99))))

Note that when exiting, this calls pool.terminate() instead of pool.close(); pool.join(). If you want to switch to the async methods this means that it will not wait for your workers to finish, but since you are not (I think), it should be fine.

Pool also automatically chooses os.cpu_count() when no number of processes is passed.
I would also move encapsulating each batch within another list into iex_get_stat, so you can just pass it a list instead (which is then actually what it says in the docstring):

def iex_get_stat(batch):
    """
    :param batch: batch is a list of stock tickers (ex: ["AAPL", "MSFT", "TSLA"]
    Gets and returns DataFrames of stats on a list of stocks
    """
    return Stock([batch], output_format="pandas").get_key_stats().T


Convert two collections of different objects into a single collection

Let's start with some sensible line continuation and indentation so we can see what's actually going on here.

var articles = context.Articles.Where(a => a.Author.ID == authorID).ToList();
var reviews = context.Reviews.Where(a => a.Author.ID == authorID).ToList();

var items = articles.ConvertAll(x => new ItemViewModel(x.ID, x.Title, x.Summary, "article", x.PublishDate))
    .Union(reviews.ConvertAll(r => new ItemViewModel(r.ID, r.Title, r.Summary, "review", r.PublishDate))
    ).Take(20)
    .OrderByDescending(i => i.publishDate));

Not perfect, but better. Remember, it's not necessary to cram all those lambdas onto a single line.

Is there a reason you're calling ToList()? That forces the execution of the query. If this is hitting a database with a lot of records, that could be potentially expensive.

You could also potentially clean up the second query a bit by moving the "converts" to the the prior queries.

var articles = context.Articles.Where(a => a.Author.ID == authorID)
    .ConvertAll(x => new ItemViewModel(x.ID, x.Title, x.Summary, "article", x.PublishDate));

var reviews = context.Reviews.Where(a => a.Author.ID == authorID)
    .ConvertAll(r => new ItemViewModel(r.ID, r.Title, r.Summary, "review", r.PublishDate));

var items = articles.Union(reviews)
    .Take(20)
    .OrderByDescending(i => i.publishDate));

Which shows us a potential opportunity to extract a method to remove the duplication.

Lastly, are you sure this does what you intend it to do? You didn't tell us exactly what you're trying to accomplish, but usually I would want to sort the results prior to selecting the top x results. I can't recall off the top of my head which order of Take and OrderBy would produce the correct results, but you should definitely double check that you're getting the information that you think you are.

*You might need to work on the Union syntax a bit. I'm not sitting in front of my IDE, so I didn't try to compile it.


A simple C++ Trie for working with strings

A couple of thoughts.

Maybe a distinction between Trie and TrieNode might make sense. So TrieNode can be defined as an inner struct within an outer class Trie.
There is no compelling reason to use a char* string representation rather than using string.
unordered_map would do just as well as a map, and possibly be faster.
You can consider iterating using a while loop instead of recursion in isContained.


I'll echo the comments and say that a profile would really help you as far as diagnosing performance problems. Profile before trying any kind of performance optimizations, because whatever you think is going on, that's probably not it. (This applies to me as well, so take everything I say below about performance with a grain of salt.)

Your code is kind of hard to read. I would review PEP 8 for style advice. In particular, spaces around your operators would help a lot. You do this pretty consistently in get_ebv_from_map, but in the driving loop, everything's all scrunched up.

Your get_ebv_from_map function is really long and has all this different stuff going on. That could be masking performance problems, and it'll make profiling harder. If you split some of it into separate functions, the profiler will give you individual performance statistics for those functions, which could be a big help.

I'm not too familiar with this library, so mock me as I deserve if my understanding of the code is egregiously wrong, but offhand, it looks to me like you're doing lots of disk IO; these lines:

for n, idx, ext in [(1, b >= 0, 'ngp'), (-1, b < 0, 'sgp')]:

    if not np.any(idx): continue
    hdulist = fits.open(fname.format(ext))  # this one
    mapd = hdulist[0].data

look like they're opening and reading a file on every iteration of the loop and extracting one value, which is the only thing used in the rest of the loop body. You then call this function in another loop, so you have a loop in which you have a loop in which you open and read a file on every iteration. I'm guessing at least one of those loops does a substantial number of iterations, so that could be a huge performance drag, since disk access is slow. And if I'm reading your code correctly, you only have two unique file extensions, 'ngp' and 'sgp', and your fname doesn't seem to be changing, so you're opening and reading the same two files over and over again, sticking the first value (hdulist[0].data) into a variable, and throwing away that value when the iteration is done.

To test this, I would try isolating that loop into its own function and profiling to see how its speed compares with the rest of the code. Something like:

def main_loop(a):
    for n, idx, ext in [(1, b >= 0, 'ngp'), (-1, b < 0, 'sgp')]:
        # Rest of the code

and call that inside get_ebv_from_map where you now have the main loop. Profile, and compare the runtime of the main_loop function with the rest of the get_ebv_from_map function.

If that does turn out to be a problem, I would try to pre-read these files somehow, or save the values you need somewhere and reuse them across invocations. If the items you're reading fit reasonably in main memory, I would try to cache them. Something like this:

for n, idx, ext in [(1, b >= 0, 'ngp'), (-1, b < 0, 'sgp')]:

    # Other necessary code
    if ext not in mapdcache:
        with fits.open(fname.format(ext)) as hdulist:
            mapdcache[ext] = hdulist[0].data
    else:
        mapd = mapdcache[ext]

mapdcache is a dictionary or list declared at some outer scope (I wrote that code like it was a dictionary). If your files are fixed across calls of get_ebv_from_map (which seems to be the case since you have mapdir and fname as constants), you can put mapdcache outside of get_ebv_from_map and you'll just have to read each file once across the entire run of the program. Otherwise it can go inside, just above this loop, and you'll at least avoid repeated file IO within one call.

I'm not familiar enough with what happens when things get bigger than main memory to offer any suggestions if your data surpasses the size of main memory.


jQuery .with() to allow better chaining and flow

The code

I'm not quite sure of the purpose of this part:

if( temp instanceof jQuery ) {
    return temp;
}

This seems to be related to the idea of chaining methods, but it prevents me from doing something like this:

var width = $('ul').show().with(function() {
    return this.width();
}

Also, when chaining, there is no benefit of only returning the result if it is an instance of jQuery, because if you try to chain methods and you return nothing from with with(), it'll result in "undefined is not a function".

You also check if the fn passed to with() actually is a function. I wouldn't do that, since this will silently ignore a wrong parameter to with(), which is very hard to debug. Instead you can just disable the check, or even better do something like this:

if(jQuery.isFunction(fn)) {
    [...]
} else {
    throw "Parameter passed to `with()` was not a function: " + fn;
}

The idea in general

I have to side with @Esailija here. While there won't be a noticeable performance difference in any modern browser (if you omit the instanceof check), I can't see the benefit of replacing a local variable with an extra level of unnecessary indentation. But that is obviously a purely personal opinion.

Aside from the extra level of indentation, I find the code using with() harder to read, since it removes context from the individual lines. I would prefer something like

$targetEl.css("background-color", "red");

to

this.css("background-color", "red");

any day, because in the former I don't have to scan the surrounding code to see what "this" currently means (which can be hard in JavaScript). Of course this is no concern in a snippet as short as your examples.


Simple class to let a thread make a clean work

This doesn't actually work as intended. You're using the CancellationTokenSource as a bool to decide whether to re-invoke the callback. That's not stopping a thread; that is not re-invoking the callback when it returns. The only reason why it appears to work for you is:

Your test callback is very short. Try inserting a long-running callback.
You print "Thread has been stopped successfully! Press any key to continue..." right after calling Cancel(). That statement is false; the only thing that has happened at that point is the CancellationTokenSource has been cancelled.

Other non-functional issues:

The CreatedThreads list doesn't hold threads, it holds CancellationTokenSources. Name the list appropriately.
Why is CreatedThreads public? It seems like something you wouldn't want the class to expose. Make it private.
This method is very strange:

private int getLastIndex()
{
    int index = 0;
    foreach (CancellationTokenSource item in CreatedThreads)
    {
        ++index;
    }

    return (index - 1);
}

Why does it not just return CreatedThreads.Count - 1 rather than iterating through the whole list? At that point there's no need for a method for it; Start can just do int currentIndex = CurrentThreads.Count - 1;

It is very awkward to have the Stop method take an index of the thread to stop, especially when an index was not supplied to or returned from Start. How is the caller of the method to know what index their thread is?

Finally I assume the only reason why you are calling Console methods in the CThread class is because you're using it for testing. Otherwise you definitely should not be doing that.


Use generic to prevent duplicate code in this case

You can take the common code in the functions in DictionaryScanner out into a common method:

    public boolean didAllRescanTasksFinish() {
        didAllXTasksFinish(rescanTasks);
    }

    private boolean didAllXTasksFinish(List<AbstractWorkerTask> tasks) {
        for (final AbstractWorkerTask task : tasks) {
            if (task.isWorking()) {
                return false;
            }
        }
        return true;
    }

Otherwise your second block of code is about as simple as you can get, because each listener has different content. If you try to remove the boilerplate you will find it gets much more difficult to understand.


SICP exercise 1.28 - miller-rabin primality test

To ensure I understood the SICP exercise correctly, I wrote my own version of the Miller-Rabin algorithm. You can look at my code and compare against yours.

With this in mind, here's my correctness-related feedback:

Your test expression, (and (not (= base 1)) (not (= base (- m 1))) (not (= exp (- m 1))) (= (remainder base m) 1)), seems to muddle up the relationship between the previous and current values. Really, what you want to find out is whether the previous value is between 2 and (- m 2) (mod m) and the current value is 1 (mod m).
Your (remainder (expmod (square base) (/ exp 2) m) m) is not optimal. All values returned by expmod should already be mod m so doing a further remainder call is pointless. You should, however, clamp the result of square to mod m.

Other style notes:

Not sure why you didn't just use a one-liner for the miller-rabin-test function:

(define (miller-rabin-test n)
  (= (expmod (+ 1 (random (- n 1))) (- n 1) n) 1))

or, if you're trying to break up the expression a bit,

(define (miller-rabin-test n)
  (define a (+ 1 (random (- n 1))))
  (= (expmod a (- n 1) n) 1))

No need for an internal function!
You can rewrite the main loop as a single or/and expression:

(define (fast-prime? n times)
  (or (zero? times)
      (and (miller-rabin-test n)
           (fast-prime? n (- times 1)))))


Cross-platform console clear
Instead of clear = lambda: os.system('cls') try to use a more cross-platform solution:
import os

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

which you can then call as:
cls()

Imports
Try writing your imports on separate lines and don't forget to remove the ones you're not using:
import datetime
import os

import requests

As you can see, I've also added an extra new line between stdlib modules and 3rd party modules. It's usually a good idea to do this as it improves readability.
Naming
In Python, the name of the variables and functions should be snake_cased. Meaning, instead of def peopleInSpace() you'd have def people_in_space() and instead of responseAstros you'd have response_astros.
Spacing & line wrapping
Try to add two new-lines (instead of one) between each function and try to end your lines somewhere between 79 - 100 chars. (I usually prefer to have more than 79 chars as specified in PEP8)
Let's see how your code looks if we take into account all the above suggestions:
import datetime
import os

import requests

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

def people_in_space():
    response_astros = requests.get("http://api.open-notify.org/astros.json")
    astros = response_astros.json()
    people = astros['people']

    people_in_spa = []
    for d in people:
        people_in_spa.append(d['name'])

    print(f'There are {astros["number"]} people in space, and '
          f'their names are: {", ".join(people_in_spa)}')

def iss_now_f():
    response_iss_now = requests.get('http://api.open-notify.org/iss-now.json')
    iss_now = response_iss_now.json()

    iss_now_lat = iss_now['iss_position']['latitude']
    iss_now_lon = iss_now['iss_position']['longitude']
    iss_now_time = iss_now['timestamp']

    print(f'The International Space Station is right now '
          f'({datetime.datetime.fromtimestamp(iss_now_time)} GMT -3) '
          f'on these approximately coordinates: {iss_now_lat} {iss_now_lon}')

def iss_next_time():
    cls()

    lat = input("What is the latitude?")
    lon = input('What is the longitude?')

    parameters = {"lat":lat, "lon":lon }
    response_iss_next_time = requests.get(
        'http://api.open-notify.org/iss-pass.json', params=parameters
    )

    iss_next_time_resp = response_iss_next_time.json()['response']
    rise_times = []
    for d in iss_next_time_resp:
        time = d['risetime']
        rise_times.append(time)

    times = []

    print("The next 5 times ISS is going to go through the given "
          "coordinates is:")

    for rt in rise_times:
        time = datetime.datetime.fromtimestamp(rt)
        times.append(time)
        print(time)

cls()

print('Press 1 to see how many people are in space right now')
print('Press 2 for getting the coordinates of the ISS right now')
print('Press 3 for seeing when the ISS will go through certain coordinates')

r = input('')

if r == '1':
    cls()
    people_in_space()
elif r == '2':
    cls()
    iss_now_f()
elif r == '3':
    cls()
    iss_next_time()
else:
    cls()
    print('Please open the program again and press only 1, 2 or 3')

Looks already a bit nicer, isn't it? ^_^
Now, let's focus on improvements:
In people_in_space function, we can use list comprehensions and also wrap that request call into a try / except guard so we can catch any possible request exceptions:
def people_in_space():
    try:
        response_astros = requests.get(
            "http://api.open-notify.org/astros.json"
        )
    except requests.exceptions.RequestException as req_exception:
        # raise an exception here or do w/e you want
        # I'm just going to exit (import sys module for this to work)
        sys.exit(f'Could not fetch people in space: {str(req_exception)}')

    astros = response_astros.json()
    people_in_spa = [d['name'] for d in astros['people']]

    print(f'There are {astros["number"]} people in space, and '
          f'their names are: {", ".join(people_in_spa)}')

The above recommendations can also be applied to iss_next_time function:
def iss_next_time():
    cls()

    lat = input("What is the latitude?")
    lon = input('What is the longitude?')

    parameters = {"lat": lat, "lon": lon}

    try:
        response_iss_next_time = requests.get(
            'http://api.open-notify.org/iss-pass.json', params=parameters
        )
    except requests.exceptions.RequestException as req_exception:
        # raise an exception here or do w/e you want
        # I'm just going to exit (import sys module for this to work)
        sys.exit(f'Could not fetch next time: {str(req_exception)}')

    iss_next_time_resp = response_iss_next_time.json()['response']

    print("The next 5 times ISS is going to go through the given "
          "coordinates is:")

    for item in iss_next_time_resp:
        print(datetime.datetime.fromtimestamp(item['risetime']))

I've removed the times list since you were appending things to it but didn't use it anywhere else. And I've also saved you some space complexity by directly iterating over the iss_next_time_resp.
// LE:
Even if your solution isn't bad at all, this is how I'd do it:
import datetime
import os
import sys

import requests

def clear_screen():
    """
    Clear the console.

    Warning: on specific OSs you might need to export the
             TERM env variable.

    """

    os.system('cls' if os.name == 'nt' else 'clear')

class OpenNotify:
    """
    API client wrapper for open-notify.org.
    """

    def __init__(self):
        self.base_url = 'http://api.open-notify.org'

    def _get(self, resource, params=None):
        """
        Abstract get method for all subsequent GET requests.

        Arguments:
            resource (str): Name of the resource.
            params (dict or None): If provided, dict of GET params.

        Returns:
            <requests.Response> object or raises exception
        """

        url = f'{self.base_url}/{resource}'

        try:
            return requests.get(url, params=params) if params else requests.get(url)
        except requests.exceptions.RequestException as req_exception:
            print(f'Could not retrieve data at url {url} because: '
                  f'{str(req_exception)}')
            sys.exit()

    @staticmethod
    def _get_json_from_response(response, resource_item=None):
        """
        Decode response to json and get a specific resource
        item if provided.

        Arguments:
            response (requests.Response): The response
            resource_item (str or None): The desired resource item or None

        Returns:
            json object or raises an exception
        """

        try:
            json_data = response.json()
        except ValueError as val_error:
            print(str(val_error))
            sys.exit()

        if resource_item:
            return json_data.get(resource_item)

        return json_data

    def _get_astronauts_info(self):
        """
        Get astronauts information.

        Returns:
            json object
        """

        response =  self._get('astros.json')
        return self._get_json_from_response(response)

    def _get_iss_data(self):
        """
        Get iss data (latitude, longitude and timestamp in GMT -3).

        Returns:
            dict
        """

        response = self._get('iss-now.json')
        timestamp = self._get_json_from_response(response, 'timestamp')

        return {
            'latitude': self._get_json_from_response(response, 'iss_position')['latitude'],
            'longitude': self._get_json_from_response(response, 'iss_position')['longitude'],
            'timestamp': datetime.datetime.fromtimestamp(timestamp),
        }

    def _get_iss_next_position_time(self, latitude, longitude):
        """
        Get iss's next position time given the latitude
        and longitude.

        Arguments:
            latitude (str): The desired latitude
            longitude (str): The desired longitude

        Returns:
            json object
        """

        response = self._get(
            'iss-pass.json',
            params={'lat': latitude, 'lon': longitude}
        )
        return self._get_json_from_response(response, 'response')

    def list_astros_info(self):
        astronauts_info = self._get_astronauts_info()
        astronauts_names = ", ".join([item["name"] for item in astronauts_info["people"]])

        print(f'There are {astronauts_info["number"]} people in space, and '
              f'their names are: {astronauts_names}')

    def list_iss_info(self):
        iss_info = self._get_iss_data()
        print(f'The International Space Station is right now '
              f'{iss_info["timestamp"]} GMT-3 on these approximately '
              f'coordinates: lat {iss_info["latitude"]} long {iss_info["longitude"]}')

    def list_iss_next_position_time(self, latitude, longitude):
        iss_next_position_info = self._get_iss_next_position_time(latitude, longitude)

        print('The next 5 times ISS is going to go through the '
              'given coordinates is:')

        for item in iss_next_position_info:
            print(datetime.datetime.fromtimestamp(item['risetime']))

def main():
    print("""Choose from the options below:

    1) See how many people are in space right now.
    2) Get the coordinates of the ISS right now.
    3) See when the ISS will go through certain coordinates.

    q) Exit
    """)

    user_input = input('Please choose an option: ')

    open_notify = OpenNotify()

    if user_input == '1':
        clear_screen()
        open_notify.list_astros_info()
    elif user_input == '2':
        clear_screen()
        open_notify.list_iss_info()
    elif user_input == '3':
        clear_screen()

        latitude = input('Please enter the latitude: ')
        longitude = input('Please enter the longitude: ')

        open_notify.list_iss_next_position_time(latitude, longitude)
    else:
        print('Invalid option')
        sys.exit()

if __name__ == '__main__':
    main()

A few things to think about:

There's still room for improvements in regards to user input validation;
The retrieved API data can change and there're no sanity checks against this;
The menu can be dynamically created in order to avoid hardcoding future next options;
The OpenNotify class might be a bit redundant since we're not making changes to any specific state variables but as the API grows and you want to add other functionality to it...this might become helpful.


Naming

IDBUtils is a name for a namespace, but for an interface representing a database system it is poorly named. Better use something like IDatabase, IDatabaseServer or IDatabaseSystem.

OpenConnection()

This method can be simplified by removing the success variable and also using a guard clause, which reduces horizontal spacing.

public static bool OpenConnection()
{
    if (String.IsNullOrWhiteSpace(DBConnectionString.Length))
    {
        return false;
    }

    try
    {
        conn = new SqlConnection(DBConnectionString);
        conn.Open();
        return true;
    }
    catch { /* Do nothing... */ }
    return false;
}


Finding number of palindrome pairs in an array

Is there a more efficient way to do this?

At the moment you have an \$O(N^2)\$ algorithm as you can see from the nested loops up to N This is not as efficient as it could be.

What you should have is an \$O(N \log N)\$ or \$O(N)\$ algorithm. To achieve \$O(N)\$, you need to pass over the words just once, ideally as you read them avoiding the need for a String[]. To do this, you need to store the words in a data structure with \$O(1)\$ (at least amortized) access. e.g. a HashSet or a HashMap.

It could look like this:

start with a HashSet of words so far. initially empty.
for each word *as you read it*.
   compute its palindrome.
   remove this palidrome from the set
   and see if it was there. i.e. Set.remove(reverse) will do this.
   if it was there you have a match
   otherwise add the word to the set.
done

Instead of three loops, you only need one.

You can see that you pass over the words just once and each operation is \$O(1)\$ with the number of words. This assumes that the words length has some natural upper bound and the length of the words doesn't matter.


Encrypting a payload for transmission over HTTP. AES256 with PBKDF2

A few, mostly minor notes:

"payload_here".getBytes();

getBytes() should have been called with a Charset. Otherwise it uses the platform's default charset which can vary from platform to platform and could result to data loss and/or other bugs.
You have local variable called salt inside the getRandomBytes method. It's a little bit confusing since the same method is called for iv too:

byte[] salt = new byte[length];

The encrypt method could throw six different types of exceptions. It's a little bit too much. All of them is a subclass of GeneralSecurityException. I'd use that instead, I don't think that clients want to handle those six different types differently.
According to the Code Conventions for the Java Programming Language class names should start with uppercase letters.

Code Conventions for the Java Programming Language, 9 - Naming Conventions
Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions