replace a text from emacs buffer to insert it vertically with emacs lisp script

Few general points about your code:

(while condition &body) form already treats &body as an implicit progn. There's no reason to wrap it in a progn.
insert accepts multiple arguments.  So, you could write (insert (mapconcat ...) "\n") instead of calling (insert ...) followed by (newline).
Traditionally, Lisp functions use - when the name of the function consists of multiple words, so, it would be better to call zip-list, not zip_list.
(let (res) ...) is exactly the same as (let ((res)) ...) but shorter.
(setq ...) can handle multiple assignments, they are executed in order they are written, so (setq a b c a) will assign b to c.  No reason to write (setq a b) (setq c a).
split-string has argument OMIT-NULLS that controls whether empty strings are included in the results.  It would be better to rely on this argument than to post-process the results.
As mentioned in the comments, there's an easier, more idiomatic way to obtain all lines of text from the buffer: (split-string (buffer-string) "\n").

Finally, unless only for the sake of an exercise in writing the zip-list function, the transpose operation calls for something like vector, not a list.  Below is a possible alternative which uses vectors to perform this operation:

(defun wvxvw/transpose-buffer ()
  (interactive)
  (let* ((lines (split-string (buffer-string) "\n"))
         (max-length
          (cl-loop for line in lines
                   maximize (max (length line))))
         (src (cl-coerce lines 'vector))
         (dst (cl-loop with matrix = (make-vector max-length nil)
                       with len = (length src)
                       for i below max-length do
                       (aset matrix i (make-vector len ?\ ))
                       finally (cl-return matrix))))
    (cl-loop for i upfrom 0
             for line across src do
             (cl-loop for j upfrom 0
                      for c across line do
                      (aset (aref dst j) i c)))
    (erase-buffer)
    (cl-loop for line across dst do
             (insert (cl-coerce line 'string) "\n"))))


Returning root

Returning the root suggests the use case

    root = slist_push_front(root, value);

However, if node allocation fails, the return value is NULL, and the whole list is lost. I recommend to change the signature to

    int slist_push_front(slist_t ** rootptr, int value);

to be used along the lines of

    if (slist_push_front(&root, value) == FAIL) {
        ....
    }

In slist_push_front, it doesn't matter whether the root is NULL or not. node->next = root will work just fine in both cases.
In slist_push_back the next pointer must become null in any case, so it seems logical to assign it once when the node is created.

I also recommend to refactor the while (temp->next) loop into a slist_get_tail function. Then slist_push_back is streamlined into

int slist_push_back(slist_t ** root, int val)
{
    slist_t * node = slist_create_node(val);
    if (node == NULL) {
        return FAILURE;
    }
    slist_t * tail = slist_get_tail(*root);
    if (tail) {
        tail->next = node;
    } else {
        *root = node;
    }


Checking the strength of a password using regexes

Concept

Current security research recommends eliminating character composition requirements. It's more important to blacklist common weak passwords. Also, passphrases are a good alternative to passwords. For the purposes of this code review, though, I'll play along with your original premise.

Style

PEP 8, the official Python style guide, recommends lower_case_with_underscores for variable names. Err_mess violates that guideline for no good reason.

Regexes

You don't need the capturing parentheses, if you're not going to do anything with the capture groups. You also don't need the + modifiers, since the requirement is for just one character of each class.

Within a character class (inside square brackets), most characters lose their special meanings. You don't need to escape ? and * with backslashes.

Design

You're performing each check twice: once to check the password validity, and a second time to gather all of the failure reasons.

This code suffers from the fact that the rules are encoded in multiple places:

the regular expressions (and their variable names)
the comments
the if statements (note especially the length check, which breaks the pattern)
the error message strings

It would be better to treat all of the rules as data, uniformly, and have a single statement that performs all of the checks.

import re

pw_to_check = input('please enter the password to be checked:')

rules = [
    ('password is too short', r'.{8}'),
    ('password needs at least one lower case character', r'[a-z]'),
    ('password needs at least one upper case character', r'[A-Z]'),
    ('password needs at least one special character', r'[-_?!@#$%^&*]'),
    ('password needs at least one number', r'[0-9]'),
]

err_msg = '\n'.join(
    req
    for req, regex in rules
    if not re.search(regex, pw_to_check)
)

print(err_msg or 'password is ok')


Cythonic Laplacian solving on a 3D regular grid

I was helped on the #scipy IRC channel by user @ngoldbaum and could substantially speed up my code by:

Avoiding to use any numpy methods in the main loop
Using OpenMP parallelization
Using true C division as there is no risk of division by zero
Avoiding to store the whole previous iteration values

…and some other minor stuff.

Here's what my solver looks like now:

import numpy as np
cimport numpy as np
cimport cython
from cython.parallel import prange
from libc.math cimport fabs

ctypedef np.float64_t DTYPE_FLOAT
ctypedef np.int_t DTYPE_INT

# dirty fix to get rid of annoying warnings
np.seterr(divide='ignore', invalid='ignore')

@cython.boundscheck(False)
@cython.wraparound(False)
cdef bint has_converged(np.ndarray[DTYPE_FLOAT, ndim=1] errors,
                        DTYPE_INT n,
                        DTYPE_FLOAT tolerance):
    cdef bint res = True
    cdef DTYPE_INT i
    for i in prange(n, nogil=True):  # is prange useful here ?
        if errors[i] > tolerance:
            res = False
            break
    return res

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
def solve_3D(np.ndarray[DTYPE_INT, ndim=1] domain_idx_i,
             np.ndarray[DTYPE_INT, ndim=1] domain_idx_j,
             np.ndarray[DTYPE_INT, ndim=1] domain_idx_k,
             np.ndarray[DTYPE_FLOAT, ndim=3] init,
             DTYPE_FLOAT tolerance,
             DTYPE_INT max_iterations,
             np.ndarray[DTYPE_FLOAT, ndim=1] spacing):
    cdef np.ndarray[DTYPE_FLOAT, ndim=3] laplace_grid = np.copy(init)
    cdef DTYPE_INT iteration = 0
    cdef DTYPE_INT n_points = len(domain_idx_i)
    cdef DTYPE_INT i, j, k, n
    cdef DTYPE_FLOAT value
    cdef DTYPE_FLOAT hi, hj, hk, hi2, hj2, hk2, factor, prev_value
    cdef np.ndarray[DTYPE_FLOAT, ndim=1] errors = np.zeros(n_points,
                                                           np.float64)
    cdef bint convergence = False

    hi, hj, hk = spacing
    hi2, hj2, hk2 = spacing ** 2

    factor = (hi2 * hj2 * hk2) / (2 * (hi2 * hj2 + hi2 * hk2 + hj2 * hk2))

    while not convergence and iteration < max_iterations:
        iteration += 1
        for n in prange(n_points, nogil=True):
            i = domain_idx_i[n]
            j = domain_idx_j[n]
            k = domain_idx_k[n]
            value = ((laplace_grid[i + 1, j, k] +
                      laplace_grid[i - 1, j, k]) / hi2 +
                     (laplace_grid[i, j + 1, k] +
                      laplace_grid[i, j - 1, k]) / hj2 +
                     (laplace_grid[i, j, k - 1] +
                      laplace_grid[i, j, k + 1]) / hk2) * factor
            prev_value = laplace_grid[i, j, k]
            laplace_grid[i, j, k] = value
            errors[n] = fabs((prev_value - value) / prev_value)

        if iteration == 1:
            convergence = False
        else:
            convergence = has_converged(errors, n, tolerance)

    return laplace_grid, iteration, np.nanmax(errors)

I think it could be a bit better if errors were checked "on the fly", removing the second for loop every while iteration. However, I did not find out to do that efficiently in a multithread prange… maybe it's not worth it!


Looping through list to create SQL Query

Using String.Join makes this kind of string operation a breeze:

// DON'T USE THIS - SQL INJECTION
string predicates = string.Join(" OR ",
        batchNos.Select(item => item.Split('/')[1])
                .Distinct()
                .Select(splitItem => $"[TraceableItem].[IdentificationNo] LIKE N'%{splitItem}'"));
string queryInsertString = "(" + predicates + ")";

You'll notice the all capital warning not to use that code. It's not just because I haven't even checked if it compiles/works, it's because this kind of thing introduces a SQL Injection Vulnerability.

What you need to do is read up on using SqlParameters in C#. You'll want to generate SQL that looks more like:

[TraceableItem].[IdentificationNo] LIKE @param1 OR [TraceableItem].[IdentificationNo] LIKE @param2

You then need to create a SqlParameter instance for each one and add that to the SqlCommand before you execute it. That's assuming you're using Ado.Net, if you're using a framework you'll have to look up the right way of doing it in the one you're using.

The danger is that if someone passes a batch number of "a/'); delete from Users; --", you'll end up creating a query that looks like:

WHERE ([TraceableItem].[IdentificationNo] LIKE N''); delete from Users; -- ...

You do not want a user to be able to do that!


So there is a flaw in this approach. It limits requests based on the current time, and not by how many requests happened in the last amount of time. Let me give you an example. We'll start at time 0 with a limit of 10 requests per every seconds.

Time | Requests (total)
--------------
0    |     0
1    |     0
2    |     0
3    |     0
4    |     0
5    |     0
6    |     0
7    |     1
8    |     3
9    |     10 # requests start getting limited
10   |     10
# your request tracking resets here and requests are no longer limited
11   |     15
12   |     18
13   |     20
14   |     20
...

Do you see the issue? Between seconds 9 to 13 (4 seconds), we had a total of 17 requests when only want to allow 10 requests per every 10 seconds.

This shows that the initial approach is flawed.

In terms of code quality, I see a few things that could be improved:

1) Variable and method names:

@keys = {} is not immediately clear what it holds. However, if it were called requests_per_ip_address I would know. Long variable names better if they describe what they're holding.

is_limited? could just be limited?

2) Working with nil you should use #nil?

For example: @keys[key] == nil could be @keys.nil?
and @keys[key] != nil could be !@keys[key].nil?

3) Don't return at the end of methods.
The last line or branch of a method is what gets returned. The explicit return is not necessary.

4) Use private. Anyone can call any method on your rate limiter, but we only want a couple of methods to be public.

5) Use a linter. Check out RuboCop. You will be surprised by all of the style rules you break!

Here is an example of how I might write this class:

class RateLimit
  def initialize(maximum_requests, time_limit)
    @maximum_requests = maximum_requests
    @time_limit = time_limit
    @user_requests = Hash.new { |h, k| h[k] = [] }
  end

  def increment(ip_address)
    return false unless user_under_limit? ip_address
    @user_requests[ip_address] << Time.now
    true
  end

  def user_under_limit?(ip_address)
    remove_first_expired_request ip_address
    @user_requests[ip_address].count < @maximum_requests
  end

  private

  def remove_first_expired_request(ip_address)
    # We can just remove the first request if it is expired
    # and that will make room for a new request
    if @user_requests[ip_address].first < Time.now - @time_limit }
      @user_requests[ip_address].shift
    end
  end
end


Matasano CryptoPals Problem 8: Detecting ECB encryption

Assuming your algorithm is correct:

Follow the pep8 style guide.
You should use range(0, len(data), block_size) so you don't have to do all the multiplication over and over.
You can use itertools.combinations to reduce it to only one loop.
You don't close the file.  You should use with to open and close the file.
You can use zip (or for python2 itertools.izip) to get both the first and second index at the same time.
You can simplify the whole thing using any and a generator expressions.
You can use str.join to simplify the printing.

Since iterators and generator expressions are lazy evaluated, it won't create any intermediate arrays.  This makes it very fast but also very readable.

from binascii import a2b_hex
from itertools import combinations, izip

def is_ecb_encoded(data, block_size):
   myrange = range(0, len(data), block_size)
   inds = combinations(zip(myrange, myrange[1:])), 2)
   return any(data[i1:i2] == data[j1:j2] for (i1, i2), (j1, j2) in inds)

filename = '8.txt'
with open(filename) as fobj:
   lines = (line.rstrip() for line in fobj)
   lines = (a2b_hex(line) for line in lines)
   lines = (line for line in lines if is_ecb_encoded(line, 16))
   print '\n'.join(lines)


#include <string>

strcpy and its friends reside within the C library header <string.h>, which should be included as <cstring> into a C++ program. Those functions then should be prepended with std::, e.g. std::strcpy. The C++ library versions defined in the C++ headers have overloads, which fixes some issues.

char* buff_;

You can replace that with std::unique_ptr<char[]>. You won't have to implement the move functions nor the destructor when using a unique_ptr data member.

Arguably, you should use a separate class for the whole memory management, following the Single Responsibility Principle. std::vector<char> is a candidate, for example.

RawString(const char* str) {
    std::cout << "rawstring normal char* ctor\n";
    buff_ = new char[strlen(str) + 1];
    strcpy(buff_, str);
    buff_[strlen(str)] = '\0';
}

The C library string functions need to compute the length of the strings at each step. This imposes additional, unnecessary work. Additionally, the last step null-terminating buff_ should be unnecessary. Both strlen and strcpy already require that str is null-terminated, and strcpy copies the null-terminator.

RawString(const char* const str) {
    std::cout << "rawstring normal char* ctor\n";

    auto const src_len = std::strlen(str);
    auto const src_len_with_nullterminator = len + 1;

    buff_ = new char[src_len_with_nullterminator];

    std::copy(str, str+src_len_with_nullterminator, buff_);
}

Also note that a user might already know the length of the string passed in; yet, there's no way to tell RawString this length.

RawString(const RawString& str)

If you do not have an very memory-constrained system, consider adding a data member that stores the size of the string. You won't have to recompute it in this and other member functions.

RawString(RawString&& other)

Your move constructor and separate move assignment-operator (see below) as well as swap should be marked as noexcept. Not only exposes this a useful guarantee to the user via a language feature, but it is also important for other types that make their behaviour dependent on the noexcept-ness of those special member functions. The usual example is std::vector<RawString>, which will provide some more efficient functions (push_back etc.) when the value type has noexcept-move-functions.

RawString(char*&& other) {
    std::cout << "rawstring move ctor\n";
    buff_ = other;
    other = nullptr;
}

For convenience, the converting constructor char const* -> RawString (similarly to std::string) is typically implicit, even though it (potentially) is not cheap to construct a RawString.

Your "moving" converting constructor is a constructor that takes ownership of a piece of memory. In my humble opinion, constructors that take ownership should be explicit. For example, it is rather simple to write this bug:

struct filesystem_entry
{
    char name[FILENAME_MAX];
};

auto x = filesystem_entry{};
RawString s = x.name;
// operate on `s` for convenience

Similarly, implicit conversions appear e.g. for returning or passing arguments to a function (where the target type is not immediately visible). The issue is not solved entirely by making the constructor explicit, though:

RawString s( name_of_file() );

If one uses direct-initialization by default, this could be realistic code in my opinion.

Of course, one could argue that such behaviour is defined precisely by the interface of RawString. I'd be surprised by such behaviour, though.

It is much safer to explicitly request a RawString to take ownership of a raw pointer:

RawString(std::unique_ptr<char[]> str) noexcept
    : buff_( str.release() )
{}

void swap(RawString& other) {
    std::swap(other.buff_, buff_);
}

Nowadays, the guideline is: Implement swap as a non-member friend function. This allows a generic usage of swap as follows:

using std::swap;
swap(x, y);

This works for both built-in types and user-defined types alike.

Note that since you have an efficient move ctor and move assignment-operator, implementing swap yourself is an optimization.

// RawString& operator=(const char* str)

With the OP's current implementation of operator=(RawString), implementing this assignment-operator is a more efficient than the implicit conversion used when it is not declared (const char* -> RawString implicit conversion, then using RawString::operator= (RawString)). However, if you implement an operator=(RawString&&), the current implementation is no more efficient than the implicit conversion used without operator=(const char*).

It is possible though to implement an optimization for this as well as the RawString::operator=(RawString const&) operator (see below), which makes this function useful.

RawString& operator=(RawString other)

Although this copy-and-swap technique is simple, it is not the most efficient(*): If the right hand side of the assignment is an lvalue, and the left hand side already has enough capacity to store the string of the RHS, you waste an allocation:

RawString myString("Hello World");
auto cpy = myString;
myString = cpy; // unnecessary allocation

It is therefore useful to define both separately:

RawString& operator=(RawString const&);
RawString& operator=(RawString&&);

If you follow my advice from above and move the memory management to another class, you can use the compiler-provided implementation for both in RawString.

(*) Howard Hinnant often refers to this, e.g. in this StackOverflow answer. See also: Herb Sutter on "Don't overuse pass-by-value"

friend const RawString operator+(const RawString& lhs, const RawString& rhs)

Although it's almost a convention now, Alexander Stepanov (the inventor of the STL) opposes the usage of + to concatenate strings. He argues that string concatenation is not commutative.

Anyway, in this implementation, we can see a possible inefficiency in the OP's allocation scheme. Classes like std::string and std::vector typically manage a block of memory that is only partially filled. This allows resizing by a certain factor once more memory is needed. An amortized constant complexity can be reached for growth this way.

Also, the OP's implementation uses C library string functions again.

Another inefficiency is that operator+ ignores the value category of its operands. Although an operator like + is supposed to not modify its operands, it can do so if they're rvalues. This allows stealing the resources of any operand. For a similar reason, returning const objects by values is detrimental. Consider:

RawString x("Hello");
auto s = x + " " + "World!";

We get a temporary string from x + " ", but cannot use its resources for the concatenation of + "World!", even if its buffer had enough capacity. Furthermore, the initialization of s requires yet another copy, since the returned RawString is const. s will be a const RawString, which prevents of course modification, even though that could be useful. Because of copy elision, no copy is made for the initialization of s. Similarly, no copy is made for an assignment of the same form, if the operator= takes a RawString by value - on the other hand, declaring operator=(RawString&&) and returning a non-const RawString from operator+ should be no less efficient.

If you provide operator overloads, you should also make sure that there is some consistency. For example, operator+ corresponds to an operator+=.

Speaking about operator overloads, an operator== and operator< (as well as its counterparts like >) are generally very useful, e.g. for sorting.

(This leads to regular types.)

Oh, and by the way: There's currently no public interface to do something with the contents of the string, sadly. Depending on this interface, the default constructor might be dangerous: It does not initialize buff_ with the address of a null-terminated string (this is a nice class invariant).

Late addition: Oops, I missed a critical bug, related to that "nice class invariant" I mentioned above: This class invariant / guarantee is assumed to exist e.g. in the copy constructor:

RawString(const RawString& str) : RawString(str.buff_)

The converting constructor that is the target of the constructor delegation requires the argument to be a null-terminated string (because of the use of strlen and friends).

Similarly, operator+ uses the same assumption.

However, this invariant is violated by the default constructor:

RawString()
{
    std::cout << "rawstring def ctor\n";
    buff_ = nullptr;
}

I can see two relatively simple solutions that maintain the class invariant:

RawString()
{
    std::cout << "rawstring def ctor\n";
    buff_ = new char[1]();
}

This makes the default constructor not noexcept (even though it's unlikely to throw), and it's probably not an efficient solution because of the allocation.

Solution two requires some more work in the destructor:

private:
static char* empty_string() {
    static char str[] = {0};
    return &str;
}

public:
RawString()
{
    std::cout << "rawstring def ctor\n";
    buff_ = empty_string();
}

~RawString()
{
    if(empty_string() != buff_) delete[] buff_;
}

Another possibility is to give up on that class invariant, and allow buffer_ == nullptr. As Loki Astari mentions in a comment to the OP, the bug can be fixed in that case by altering the code in RawString(char const*) and operator+.


Try and except clauses for appending elements in lists

except: raise Exception is awful.

It converts all errors to Exception.

This means errors that have nothing to do with Exception like BaseException and KeyboardInterupt are now something they semantically are not.
This also means if you have a KeyError then it's magically the same as any other error.

It doesn't even raise an exception instance, Exception().
There's no need for it, just remove it from your code.

If you weren't appending to different lists then we could see that all we need is a basic for loop.

for proj in issue.affected_projects[:3]:
    affected.append(proj)

Since you have to append to other lists you can zip over them.

for affected, proj in zip(affected_projects, issue.affected_projects):
    affected.append(proj)

Since you need to default to '' you can just extend issue.affected_projects to these values.

affected_projects = [[], [], []]
for issue in project:
    for affected, proj in zip(
        affected_projects,
        issue.affected_projects + 3*['']
    ):
        affected.append(proj)

We can remove the need for affected.append by moving the zip up one loop.

affected_projects = zip(*(
    (issue.affected_projects + 3*[''])[:3]
    for issue in project
))
pd.DataFrame(zip(*affected_projects))

Since you are ziping affected_projects and you're zipping issue.affected_projects you don't really need to zip at all.

df = pd.DataFrame(
    (issue.affected_projects + 3*[''])[:3]
    for issue in project
)


Getting current weather data using OpenWeatherMap API

Your code is very nicely split into functions. As a next step I would split it to classes. What you want to do is

Collect the data for a given city
Convert it into a schema that fits your purposes and write it to a file

In my opinion, the scheduling of this job should be done elsewhere, e.g. cron

Although the +-sign concatenates strings correctly it is not the most readable way to do it. There are many ways to format strings in Python3 and I tend to use f-strings.

Pandas is a great library for data analysis and data "wrangling" but to use it to write csv files is simply an overkill. Usually, you want to keep your virtual environmets as small as possible and use the standard library as much as possible. In this case the csv library is all you need.

I think you got somehow lost when modifying the API response. There is absolutely no need to convert it from dictionary to json and then back to tabular form. Simply use the dictionary that requests gives you, get the data you need and write it to a file.

Here's my code:

from os.path import isfile
from io import StringIO
from datetime import datetime
from csv import DictWriter
import requests

URL = 'https://pm1aapplicantsdata.blob.core.windows.net/databases/CitiesWeather/CitiesWeather.csv'

class CityWeatherCollector(object):
    """Class to collect weather information for a given city from openweathermap.org
    """

    base_url = "http://api.openweathermap.org/data/2.5/weather?"
    apikey = 'xxxxxxxxxxxxxxxxxxxxxxx'

    def __init__(self, city, code):
        self.city = city
        self.code = code

    @property
    def full_url(self):
        return self.base_url + f"appid={self.apikey}&q={self.city},{self.code}"

    def fetch_data(self):
        response = requests.get(self.full_url)
        if response.status_code == 200:
            #returns a dictionary
            return response.json()
        else:
            raise WeatherCollectionError(f"Response from API was: {response.status_code}")

class WeatherCollectionError(Exception):
    pass

class WeatherDataWriter(object):

    def __init__(self, full_filepath):
        self.full_filepath = full_filepath

class WeatherData(object):
    """Class for a representation of the data"""

    def __init__(self, name, country, temp, humidity, pressure, visibility, wind_speed, timestamp=datetime.now()):
        self.name = name
        self.country = country
        self.temp = temp
        self.humidity = humidity
        self.pressure = pressure
        self.visibility = visibility
        self.wind_speed = wind_speed
        self.timestamp = timestamp

    @staticmethod
    def create_from_json(json_dict, timestamp=datetime.now()):
        return WeatherData(
            name=json_dict['name'],
            country=json_dict['sys']['country'],
            temp=json_dict['main']['temp'],
            humidity=json_dict['main']['humidity'],
            pressure=json_dict['main']['pressure'],
            visibility=json_dict['visibility'],
            wind_speed=json_dict['wind']['speed'],
            timestamp=timestamp
        )

    def write_one(self, outfile):
        weather_data = self.__dict__
        # if file exists, append
        csv_writer = DictWriter(
            out_file,
            fieldnames=list(weather_data.keys()),
            delimiter=',',
            lineterminator='\n'
            )
        #if the file is empty write header
        if outfile.tell() == 0:
            csv_writer.writeheader()
        csv_writer.writerow(weather_data)

def get_cities(url=URL):
    response = requests.get(url)
    if response.status_code == 200:
        decoded_response = StringIO(response.content.decode('utf8'))
        # pop the headings
        next(decoded_response)
        for line in decoded_response:
            city, code = tuple(line.strip().split(','))
            yield CityWeatherCollector(city, code)

if __name__ == '__main__':
    timestamp = datetime.now()
    with open('data.csv', 'a') as out_file:
        for collector in get_cities(URL):
            # add error handling
            full_data = collector.fetch_data()
            data = WeatherData.create_from_json(json_dict=full_data, timestamp=timestamp)
            data.write_one(out_file)


Best practice-creating a good PDO connection

Please, never use procedural code-style with object oriented libraries.
For php5+: this is not good code-style, please, see article about Object Oriented Programming; for php5-: this is tolerable variant(but I don't remember if php4 has had PDO).

After learning something about OOP, try to read something about MVC(Model-View-Controller) and Design Patterns(ex.: "GOF: Design Patterns")

P.S. Sorry if it seems roughly for you. But if you want to write best code - it's the only way.


HTTP Get & Post code with slow performance

I personally haven't used anything HTTP-related in Java yet, and thus can't talk about your performance. What I can see though is the following code:

if(protocol.startsWith("https"){
    securedConnection = true;
} else {
    securedConnection = false;
}

I will assume you have securedConnection as a private classwide field, so I won't talk about the fact that you only use it to determine the port in the method scope.

the fun thing is, your code could be written in one line:

securedConnection = protocol.startsWith("https");

if you now inline protocol (Eclipse Alt + Shift + i) you get following line:

securedConnection = connectionUrl.substring(0,5).toLowerCase().startsWith("https");

you see that the call to substring is unneccesary.

You also have a large duplication in itself with the methods processPostRequest() and processGetRequest. they are actually exactly the same apart from the last line:

get = new HttpGet(uri.getPath()+query_string);
post = new HttpPost(uri.getPath());

you might want to move them into a method like this:

private enum Type{
    GET, POST
}

private HttpRequest processRequestOfType(Type t){
   uri = Uri.parse(connectionUrl);
   securedConnection = connectionUrl.toLowerCase().startsWith("https");
   host = securedConnection ? new HttpHost(uri.getHost(), 443, uri.getScheme())
              : new HttpHost(uri.getHost(), 80, uri.getScheme());
   request = t == Type.GET ? new HttpGet(uri.getPath()+query_string)
              : new HttpPost(uri.getPath());
   return request;
}

Lastly I saw that in your method httpGetResponseStream() you have the parameter request, which is never used in the code you posted.


Simple structure that would contain validation errors messages

Naming
Class names in C#, whether they're for a static, non-static, internal, public, private, abstract, nested or on-its-own class, should be PascalCase.
Find the intruder:
public class _Notice
public class _Exporter
public class _Importer
public class _Shipping
public class Address

 Only Address is correct!

Keep the underscore prefix for private fields, it seems you're using prefixes only to avoid name clashes - this smells, because in naming what's important is consistency - using arbitrary prefixes is bad practice.
Also, it's possible the nested types are not warranted, but it's very hard to tell without seeing how you're using this ValidationError static class.


Escalation approval tool, copy to clipboard via Python

The main part of your program is only

def copy_string_to_clipboard(self):  # Copy to the windows clipboard
    cb = Tk()
    cb.withdraw()
    cb.clipboard_clear()
    cb.clipboard_append(self.full_string)

the rest being used only as a formatting tool. You should thus focus into making such formatting as clear as possible.

But first of, you may want to read about docstrings as your comment should be one:

def copy_string_to_clipboard(self):
    """Copy to the windows clipboard"""

    cb = Tk()
    cb.withdraw()
    cb.clipboard_clear()
    cb.clipboard_append(self.full_string)

So now, onto cleaning a bit everything around this function.

First off, you don't need a class with 3 other functions just to concatenate two strings. Based on your opening variable, what you need to do is simply:

user = read_username()
assignation = raw_input('Escalate to where? ')
copy_to_clipboard(
        'Ticket has been reviewed and approved by {}. '
        'Ticket assigned to {}.'.format(user, assignation))

where copy_to_clipboard has been slightly modified to accept the whole string as argument:

def copy_to_clipboard(text):
    """Copy the content of a string to the windows clipboard"""

    cb = Tk()
    cb.withdraw()
    cb.clipboard_clear()
    cb.clipboard_append(text)

The last thing to do is to simplify a bit the reading of the user config file. It's a bit of a shame to be required to run the program twice in order to create a file if it doesn't exist. Instead, you could try to read the file and, if it fails, ask the user for its content:

def read_username(filename='esc_name.txt'):
    """Get the user's name from config file or command line"""

    try:
        with open(filename) as f:
            return f.readline()
    except OSError:
        pass

    # If we are here, we couldn't read the configuration
    # file so ask the user an try to save its choice
    username = raw_input('Enter what you want appear on escalations (be specific): ')

    try:
        with open(filename, 'w') as f:
            f.write(username)
    except OSError:
        pass

    return username

But this function assumes we are in the right directory, which may not exist yet. Let's tackle that as well:

from getpass import getuser

def setup(program_dir='esc'):
    """Create our own directory structure and move to the right place"""

    appdata = r'C:\Users\{}\AppData\Roaming'.format(getuser())
    os.chdir(appdata)
    if not os.path.exists(program_dir):
        os.mkdir(program_dir)
    os.chdir(program_dir)

as you can see, I used getuser from getpass directly without having to create a wrapper that just remove 1 level of nesting.

Also, if I recall correctly, os.environ['APPDATA'] should contain the value we are building into appdata. So you could simplify it to:

def setup(program_dir='esc'):
    """Create our own directory structure and move to the right place"""

    os.chdir(os.environ['APPDATA'])
    if not os.path.exists(program_dir):
        os.mkdir(program_dir)
    os.chdir(program_dir)

Putting it all together, you can end up with:

import os
from Tkinter import Tk

def copy_to_clipboard(text):
    """Copy the content of a string to the windows clipboard"""

    cb = Tk()
    cb.withdraw()
    cb.clipboard_clear()
    cb.clipboard_append(text)

def setup(program_dir='esc'):
    """Create our own directory structure and move to the right place"""

    os.chdir(os.environ['APPDATA'])
    if not os.path.exists(program_dir):
        os.mkdir(program_dir)
    os.chdir(program_dir)

def read_username(filename='esc_name.txt'):
    """Get the user's name from config file or command line"""

    try:
        with open(filename) as f:
            return f.readline()
    except OSError:
        pass

    # If we are here, we couldn't read the configuration
    # file so ask the user an try to save its choice
    username = raw_input('Enter what you want appear on escalations (be specific): ')

    try:
        with open(filename, 'w') as f:
            f.write(username)
    except OSError:
        pass

    return username

if __name__ == '__main__':
    setup()
    user = read_username()
    assignation = raw_input('Escalate to where? ')
    copy_to_clipboard(
            'Ticket has been reviewed and approved by {}. '
            'Ticket assigned to {}.'.format(user, assignation))
    print 'Press CTRL-V to paste the approval.'


Refactoring this legacy application to a cleaner state (continued)

you should move

child.Children.Add(grandChild);

outside of your if statements like so:

    foreach (var item in gmcListItems)
    {
        var customerReport = (CustomerReport) item.dataObject;
        var grandChild = AssembleGrandChild(child, customerReport);
        if (item.value.Equals(initialReportType))
        {
            if (!item.key.Equals(initialCrs))
            {
                initialCrs = item.key;
                parent.Children.Add(child);
                child = AssembleNode(item.key, parent);
            }
        }
        else
        {
            initialReportType = item.value;
            initialCrs = item.key;
            parent.Children.Add(child);
            nodes.Add(parent);
            parent = AssembleNode(item.value);
            child = AssembleNode(item.key, parent);
            grandChild = AssembleGrandChild(child, customerReport);
        }
        child.Children.Add(grandChild); // <--
    }
    parent.Children.Add(child);
    nodes.Add(parent);

Otherwise you are going to have a whole lot of duplicates.


C - Learning Linked Lists, Pointer Manipulation - Store some ints, print and free memory

Naming
It's unconventional to name a type with all-uppercase - we normally reserve those names for preprocessor macros, to warn readers that they need treating with care.  Avoid such names for ordinary identifiers.
Avoid using identifiers that begin with an underscore - in many situations, those names are reserved for use by the implementation, which could conflict with your own uses.
Allocation
Let's look at this section:

    NODE *newnode = (NODE *) malloc(sizeof(NODE));
    newnode->value = n;
    newnode->next = NULL;

There's a serious bug here.  Remember that malloc() can return a null pointer.  It's essential to check that newnode is not null before we dereference it using * or ->.
Because malloc() returns a void*, it's not necessary or desirable to cast the result - we can assign it directly to newnode.  Also, when computing the size, we can avoid repeating the type of the allocation by writing sizeof *newnode for the size (this has more value when the allocation is far from the declaration, but it's a good habit to be in).
That gives this replacement:
    Node *newnode = malloc(sizeof *newnode);
    if (!newnode) {
        fputs("Allocation failed\n", stderr);
        return EXIT_FAILURE;
    }

    newnode->value = n;
    newnode->next = NULL;

Reading input
Another function whose return value must be checked is scanf().  If I enter something that's not a number, or if I close the input stream, then we don't write to n here:

scanf("%i", &n);

We need to check the return value and test whether the expected number of items were successfully converted.  Something like this:
int getinteger(void)
{
    int n = 0;
    printf("Enter integer: ");
    fflush(stdout);
    while (scanf("%i", &n) != 1) {
        if (feof(stdin)) {
            /* no point retrying! */
            fputs("Read failure\n", stderr);
            exit(EXIT_FAILURE);
        }
        printf("Invalid input! Enter integer: ");
        fflush(stdout);
        scanf("%*[^\n]");       /* discard rest of line */
        /* newline remains, but will be discarded by scanf("%i") */
    }
    return n;
}

Notice that there's a lot more code for dealing with the unexpected than with the "happy path" - that's a common experience when reading input using C.
Memory management
Apart from the lack of checking when malloc() is used, the memory management is great.  No leaks, double-frees, or use of uninitialised, unallocated or released memory.
Efficiency
Notice that every time we add a node, we have to start from the head, and traverse the whole length of the list to get to the tail.  This becomes more and more work as the list gets longer - sometimes likened to Schlemiel the Painter.  We can make this more efficient, though at the cost of some extra storage, by maintaining a pointer to the tail of the list as well as the head.
Other improvements
We don't need to pass a pointer-to-pointer into printlist(); a plain Node * is fine:
void printlist(Node *p)
{
    for (;  p;  p = p->next) {
        printf("%i\n", p->value);
    }
}

When we're looking for the list tail, we can simplify by starting p at head rather than first assigning NULL:
        Node *p = start;
        while (p->next) {
            p = p->next;
        }
        p->next = newnode;

In the main loop in main(), n shouldn't be declared in the for initializer, as it's not part of the loop control.
If we define main() last, the definitions of the other functions can act as their declarations, so no need to forward-declare them.

Improved code
Note: I haven't addressed the issue mentioned above in "Efficiency".
#include <stdio.h>
#include <stdlib.h>

/* number of nodes to create in list */
#define N 5

typedef struct node {
    int value;
    struct node *next;
} Node;

/* Prompt on stdout, and read a number from stdin */
int getinteger(void)
{
    printf("Enter integer: ");
    fflush(stdout);

    int n;
    while (scanf("%i", &n) != 1) {
        if (feof(stdin)) {
            /* no point retrying! */
            fputs("Read failure\n", stderr);
            exit(EXIT_FAILURE);
        }
        printf("Invalid input! Enter integer: ");
        fflush(stdout);
        scanf("%*[^\n]");       /* discard rest of line */
        /* newline remains, but will be discarded by scanf("%i") */
    }

    return n;
}

void printlist(Node *p)
{
    for (;  p;  p = p->next) {
        printf("%i\n", p->value);
    }
}

void freelist(Node *p)
{
    while (p) {
        Node *next = p->next;
        free(p);
        p = next;
    }
}

int main(void)
{
    Node *start = NULL;

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

        Node *newnode = malloc(sizeof *newnode);
        if (!newnode) {
            fputs("Allocation failure\n", stderr);
            return EXIT_FAILURE;
        }

        newnode->value = n;
        newnode->next = NULL;

        if (!start) {
            start = newnode;
        } else {
            Node *p = start;
            while (p->next) {
                p = p->next;
            }
            p->next = newnode;
        }
    }

    printlist(start);
    freelist(start);
}


Four years, 1400 views, and two dozen upvotes before a review on a site dedicated to code reviews points toward unreviewability as a prominent feature of the code. What hinders reviewability is, I think, the high level of cognitive load the code places on anyone reading it.

Reading

The cognitive load begins at the top level. Merge-sort is a well documented algorithm. Like many people interested in programming, I wrote an implementation for an algorithms class. It makes a good assignment because the details are non-trivial (and discovering those details was serious work seventy years ago when the John Von-Neumann for which computing's Von-Neumann Architecture is named, did so..."how serious?" one might ask and the answer would be "Manhattan Project serious"). I imagine I'm like some other people in that I've forgotten the ins and outs of my implementation and recycled whatever synapses were storing the pseudo-code to something else. For me, merge-sort is vaguely familiar in a sort of \$\mathcal{O}(n\log n)\$ sort of way since that's the fact that's most likely to be relevant at the sorting level of abstraction.
For the purposes of this review, I'll say that the next level down is the top level of the implementation. Here the question claims a clever implementation detail: calculating the length of the list only once. I don't recall how my implementation calculated length or whether it did...I think I used vectors/arrays rather than lists [I wrote it in either Clojure or Racket]. Anyway, being clever makes the code harder to review.
At the next level down, the structure induces additional cognitive load. At best the mixture of define and let/let* is inconsistent style. At worst, the let's just make for less readable code of the sort that made nested define's worth implementing in Scheme itself.
Finally, there's variable names.

Advice

Help the reader by commenting the code. Don't require expertise in merge-sort as a pre-requisite to understanding. Consider using something like the HtDP Program Recipe as a starting point. Explain the algorithm and use the terms of that explanation in the implementation.
I'm reminded of Kernighan's Lever: Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it? Looking at the code, it isn't obvious where the innovation is implemented. Even after I obtain some level of merge-sort knowledge, I still have detective work to understand the innovation. Make the innovation explicit.
Make everything explicit using define rather than let/let* the syntax is better and the high level concepts can be articulated together rather than mixed in among the implementation details, e.g. merge can be defined alongside truthy=?, mid, etc.
There's no need to name parameters/variables using the criteria for minified JavaScript. l and r might be abstractions 'left' and 'right' but left and right are not abstractions that are explicit in the code. It's only via research that a reader might possibly make the connection.

A bit more on Item 2: If performance is a concern the question of why lists and parameter passing  rather than vectors or some other data structure seems relevant. Going further, benchmarking is probably the best justification for added complexity:

  Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

Fast sorting seems to be a place where using an FFI is the road to meaningful improvement for interestingly sized data.


The main issue I see with this code is in the fetchFilesAsImages() function. You're needlessly building a results array to return at the end of the call fetchFilesAsImages(). Why not just take advantage of the fact that Promise.all() will already return a list of what each promise resolved to. So, you could instead write fetchFilesAsImages() as follows:
export async function fetchFilesAsImages(filesUrls) {
  return await Promise.all(
    filesUrls.map(async ({ url, category }) => {
      const data = await fetchBlob(url);
      return await convertPDF({ data }, category);
    })
  );
}

One other thing I would suggest is to just use async/await syntax everywhere. Your fetchBlob() could look a little cleaner with it:
export async function fetchBlob(url, opts = {}) {
  const res = await fetch(url, opts);
  if (!res.ok) throw new Error(res.statusText);
  return res.blob();
}


autoloader class fine tune to be usable in every project

I don't see a reason to use static methods here, consider using plain 'ol methods.
Why throw an exception? PHP will issue a fatal error when a class is used but not defined.
Since you are not using spl_autoload_register(), I'm not sure yours will play nicely with other autoloaders
Why not simply use the PSR-0 sample autoloader?


Display related images based on text name

A few thoughts come to mind here:

You are not properly using inheritance in your CSS.  You should probably have one definition for .product-options ul.options-list .label>label which contains every single CSS declaration except for the actual background image. As these will not change.  Then just have definitions for .product-options ul.options-list .label>label.* (where * is green, black, etc.) that are one line each (specifying background-image), as that is the only part that changes based on color.
You might consider not using images at all in favor of pure CSS.  This could actually give the benefit of potentially not having to declare per-color CSS styles at all, in favor of just changing the background color value on the elements to one of the valid CSS named colors. Here are CSS-only examples for different shapes. This would actually perform better as there would be no images to download at all.
Your variable names are not very meaningful. For example inner might better be called labels or similar (or $labels if you use the convention of pre-pending jQuery collections with $). Perhaps color instead of classN.
You might need to give up hope of individually checking each label element text as being one of allowed color values. Or look to solutions like these to provide validation that the color names are good.
Since you are working against a jQuery collection,  you might consider using $.each() as your iterator rather than a for loop.

Combining these approaches might mean you can simplify your code down to:

var jQuery = $.noConflict();
jQuery(document).ready(function(){
    var $labels = jQuery(" .product-options ul.options-list .label>label");
    $labels.each(function() {
        var color = $(this).text();
        // perhaps validate color here as noted above in link
        if(colorIsValid(color)) {
            $(this).css('background', color);
        } else {
            throw new RangeError('Unexpected color value.');
        }
    }
});


Restructuring loop logic and its effect on allocations

This is very idomatic, in principle.  The loop refactoring is exactly what I would have done.

Here's some other suggestions:

const Coords{T} = NTuple{N, T} where N

function _octaves(coords::Coords{T}; octaves::Int=1, persistence::T=one(T)) where {T<:Real}
    if octaves < 1
        # prevent zero division
        throw(DomainError(octaves, "`octaves` must be at least 1!"))
    end

    total = zero(T)
    maxval = zero(T)

    for octave in 1:octaves
        p = octave - 1
        frequency = 2 ^ p
        amplitude = persistence ^ p

        maxval += amplitude

        scaled_coords = coords .* frequency
        total += simplexnoise(scaled_coords...) * amplitude
    end

    return total / maxval
end

Using one and zero to ensure type stability (a very important concept, which you should read about if you don't know it!)
Replacing some intermediate updates by explicit powers.  The calculation of frequency is trivial to the compiler, since it is an integer power of 2.  amplitude might do some unnecessary work; I think it is clearer that way, and not worth the microoptimisation, but you'd have to test that for your use case.

The choice of type for coords is really determined by the rest of the code.  If this is only ever going to be used for coordinates of bounded dimension, I'd very much prefer a tuple as I wrote above.  If you use vectors all the way down (this looks a bit like signal processing?), then staying with Coords{T} = Vector{T} is easier.

While not part of the question, it might be nicer to have simplenoise work on an iterable, not a varargs argument.  Possibly even as simplenoise(frequency, coords), then the allocation of scaled_coords is removed.

If there's any chance that the summation will overflow, take a look at Base.widen.  Also, you might want to ensure that octaves < 8 * sizeof(Int) or something like that, and add this to the check at the beginning.

If this is really the hot part of some code to be optimized, with octaves being constant over many calls, there's the possibility to write a @generated function to unroll the loop completely, but unless it is critical, it's not worth it.

As for the difference in benchmarking: first, you should do that with BenchmarkTools.jl, not @time.  Then, I haven't measured myself, but it's quite surely due to the intermediate inputs array you construct.


Code minimizer - Remove unnecessary whitespace

Here's something that gets the same answer using different techniques:

(def safe-neighbors
  (set "(){}[]\" \t\n"))

(defn whitesp? [ch]
  (Character/isWhitespace ^Character ch))

(defn del-white [s]
  (reduce #(if (and (whitesp? %2)
                    (whitesp? (last %1)))
             %1
             (str %1 %2)) "" s))

(defn squeezable? [[a b c]]
  (and (whitesp? b) (or (safe-neighbors a) (safe-neighbors c))))

(defn elide [triples]
  (let [squeezabilities (drop-last (cons true (map (complement squeezable?) triples)))]
    (->> (map vector squeezabilities triples)
         (filter first)
         (map (comp first second)))))

(defn squeeze-safe [s]
  (apply str (apply str (->> s (partition 3 1) elide)) (take-last 2 s)))

(defn minimize-code-2* [code-str]
  (->> code-str
       del-white
       squeeze-safe))

(defmacro minimize-code [& body]
  (minimize-code-2* (apply str body)))

(defn x-1 []
  (minimize-code (fn [a]    (+ a   1))))

In particular it removes recursion from being the crux of the code. Loop/recur recursion can solve most problems, but can quickly become liable to frailty and difficult to reason about as more and more loop variables are added.

Here the starting off point was to think that partition can be used to look at the neighbouring characters by only grabbing three characters at a time. Thus partition can replace recursion. You know exactly what is going on with partition, however recursion is less focused, takes more time to comprehend and is prone to atrophy.

Here removing white-space and seeing if the final squeeze(*) can be done are two different operations, done on different parses through the input. Thus when writing (and reading) the code you can concentrate on one simple thing at a time.

Here squeezable? can be replaced by can-remove-cur-char?, as the latter is almost certainly more well thought out than my effort!

(*) Squeeze as in squeeze out the unnecessary white-space between neighbouring characters


Overwrite disk space for the purpose of deleting old data

Make a habit of initializing variables. Your scanfmight fail:

scanf("%d", &number_of_files);

What happens if I answer "many"? Well, first of all, scanf will return 0, and next number_of_files won't get changed. So its value is unknown. If we use it, we end up with undefined behaviour, which is a fancy term to say "we have no idea what will happen".

So in order to at least prevent something like number_of_files = 1000000000 and number_of_values = 10000000 just because the input failed, make sure to initialize your values and maybe check whether scanf succeeded:

int main()
{
    int number_of_files  = 0;
    int number_of_values = 0;

    srand(time(NULL));

    printf("before using this program create a folder with the name \"folder\"\nin the same folder this program is located\n");
    printf("number of files: ");

    if(scanf("%d", &number_of_files) != 1) {
       // handle the error?
    }
    printf("number of values: ");

    if(scanf("%d", &number_of_values) != 1) {
       // handle the error?
    }

    create_files(number_of_files, number_of_values);
}

Note that your usage is misleading: the folder has to be located in the folder the program is run, not located.

Let the compiler help you

Note that I got rid of the int i? You declared it, but you've never used it. You probably had all of your program in your main and decided to refactor (good!), but you forgot not only the i, but to return something in create_files. Both of these mishaps could have been found with compiler flags:

$ gcc -Wall -pedantic main.c

main.c: In function 'int main()':
main.c:10:9: warning: unused variable 'i' [-Wunused-variable]
     int i;
         ^
main.c: In function 'int create_files(int, int)':
main.c:44:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }
 ^

Initialize the seed once

I've moved the srand call into main. That way there will be only one call to srand, regardless of how many times you call create_files. That's handy since

we can now reconstruct the flow if we print the seed
we can reconstruct the flow even if we call create_files multiple times
we don't have to worry about calling create_files twice in the same second

Simplify and continue to check errors

You can use sprintf to print your file_name directly:

char file_name[50] = "";
sprintf(file_name, "./folder/trash-%015d");

This will format file_name as "./folder/trash-000000000000001". Since every file name has the same length, the sorting is somewhat better, and the trash- prefix will simplify the users life in case they accidentally had a folder called folder (but they should really rename that folder).

That being said, you should check whether you were able to open that file at all, and whether you could actually write to it. Remember, you're trying to fill a disk (not memory) to the brim. If it's full, you cannot continue to write, and either fopen or fprintf will fail:

if(!(file = fopen(file_name, "w+")))
{
    perror("Could not open file");
    return i;
}

for(int j = 0; j < number_of_values; j++)
{
    int random_value = rand();
    if(fprintf(file, "%d", random_value) < 0)
    {
        fclose(file);
        return i;
    }
}

Note that I return i because I think you've wanted to return the number of created files, but I'm not sure. If you didn't want to return anything at all, change create_files return type to void.


Identifying originating country of an IP address

the only issues that I see with this code so far is formatting.

class IPRangeRepository : IDisposable
    {
        public IPRangeRepository(string fileName)
        {
            this.fileName = fileName;
            xmlReader = XmlReader.Create(fileName);
        }

This indentation is not standard, it should look like this

class IPRangeRepository : IDisposable
{
    public IPRangeRepository(string fileName)
    {
        this.fileName = fileName;
        xmlReader = XmlReader.Create(fileName);
    }

and your if statements inside the while loop are not easy to read.

        while (xmlReader.Read())
        {
            // Ok instantiate object and then do comparison...
            if (xmlReader.Name == "IPRange") {
            var ipRange = IPRange.TryParse(xmlReader["Value"]);
            if (ipRange.IsIPAddressInRange(adress)) return xmlReader["Country"];
            }
        }

this is how I prefer to write this code

while (xmlReader.Read())
{
    // Ok instantiate object and then do comparison...
    if (xmlReader.Name == "IPRange") {
        var ipRange = IPRange.TryParse(xmlReader["Value"]);
        if (ipRange.IsIPAddressInRange(adress))
        {
            return xmlReader["Country"];
        }
    }
}

the return is a little too complex for something that I would one line, and most of the time if I can one line something it's going to look better as a ternary statement, this isn't one of those instances.

Always indent code inside of any block.


Find total number of paths in a matrix of 0's and 1's

Recursion is not recommended.  First, you would likely end up repeating calculations for cells that are approached from multiple paths.  Second, the call stack would be as deep as the longest path, and you could easily crash with a StackOverflowError for a large maze.

Instead, I recommend using dynamic-programming, building a 2D table where each entry is the number of paths from the start to that location.  Every paths[r][c] is calculated exactly once, and in an order that is gentle to the cache.

public static int count(int[][] a) {
    int[][] paths = new int[a.length][a[0].length];
    if ((paths[0][0] = a[0][0]) == 0) {
        return 0;
    }
    for (int c = 1; c < a[0].length; c++) {
        paths[0][c] = a[0][c] * paths[0][c - 1];
    }
    for (int r = 1; r < a.length; r++) {
        paths[r][0] = a[r][0] * paths[r - 1][0];
        for (int c = 1; c < a[r].length; c++) {
            paths[r][c] = a[r][c] * (paths[r - 1][c] + paths[r][c - 1]);
        }
    }
    return paths[a.length - 1][a[0].length - 1];
}

You can even even build the paths one row at a time, while the maze a is being loaded. Furthermore, it is possible to modify the code to use less memory, since only the last two rows of paths are relevant at any given time. However, for simplicity, I haven't done that here: if you can afford to keep the entire a in memory, then you can probably also afford to keep another 2D array of the same size.


Is there a way to make my Rock, Paper, Scissors game more concise?

Just build an object with the associativity.

// what wins to what
var winsTo = {
  'rock': 'scissors',
  'paper': 'rock',
  'scissors': 'paper',
};

// invalid selected
if (!(choice1 in winsTo && choice2 in winsTo)) {
  alert("bad choice !");
  return;
}

// same choice => equality
if (choice1 == choice2) {
  alert("Equality!");
} else if (winsTo[choice1] == choice2) {
  alert("choice1 won!");
} else {
  alert("choice2 won!");
}


This line looks suspicious:

            if person.email: self.request.get('email')

I assume it should be:

            person.email = self.request.get('email')

Your code seem to be using excessive indentation. The python standard is four space per level.

You are using templateValues but don't seem to define it anywhere.

To refactor this, I'd start by removing the section of that that's different between the two methods into their own function:

# This class manage the user account
class MyAccount(webapp2.RequestHandler):

    def show_user(self, user):
        # Get the actual user data
        data = Person.gql("WHERE username = :nick",
                                            nick=user.nickname()).get()
        # Test if we found the user
        if data:
            templateValues['data'] = data
            template = jinja_environment.get_template('myAccount.htm')
        else:
            templateValues['custom_msg'] = "The logged user is not available."
            template = jinja_environment.get_template('customMessage.htm')

        return template, templateValues

    def get(self):
        """ Shows actual user account """

        # Get actual user
        user = users.get_current_user()
        if user:
            template, templateValues = self.show_user(user)
        else:
            templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account"
            template = jinja_environment.get_template('customMessage.htm')

        # Render the page
        self.response.out.write(template.render(templateValues))

    def update_user(self, user):
        # Get the actual user data
        person = Person.gql("WHERE username = :nick",
                nick=user.nickname()).get()
        # Test if we found the user
        if person:
            person.username = self.request.get('username')
            person.password = self.request.get('password')
            person.email = self.request.get('email')
            person.name = self.request.get('name')
            person.lastname = self.request.get('lastname')
            person.idnumber = self.request.get('idnumber')

            templateValues['data'] = person
            template = jinja_environment.get_template('myAccount.htm')
        else:
            templateValues['custom_msg'] = "The logged user is not available."
            template = jinja_environment.get_template('customMessage.htm')

        return template, templateValues

    def post(self):
        """ Saves user updated data """
        # Get actual user
        user = users.get_current_user()
        if user:
            template, templateValues = self.update_user(user)
        else:
            templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account."
            template = jinja_environment.get_template('customMessage.htm')
        # Render the page
        self.response.out.write(template.render(templateValues))

The only thing different between post and get is the function they call. We'll just pass the function as a parameter to a new function.

    def request(self, handler):
        """ Shows actual user account """

        # Get actual user
        user = users.get_current_user()
        if user:
            template, templateValues = handler(user)
        else:
            templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account"
            template = jinja_environment.get_template('customMessage.htm')

        # Render the page
        self.response.out.write(template.render(templateValues))

    def get(self):
        return self.request(self.show_user)

    def post(self):
        return self.request(self.update_user)

The current code repeats calls to get_template a lot. So we'll refactor it so that it only happens once. We'll just store the name of the template in a variable and load it just before we render it.

def show_user(self, user):
    # Get the actual user data
    data = Person.gql("WHERE username = :nick",
                                        nick=user.nickname()).get()
    # Test if we found the user
    if data:
        templateValues['data'] = data
        template = 'myAccount.htm'
    else:
        templateValues['custom_msg'] = "The logged user is not available."
        template = 'customMessage.htm'

    return template, templateValues

def request(self, handler):
    """ Shows actual user account """

    # Get actual user
    user = users.get_current_user()
    if user:
        template, templateValues = handler(user)
    else:
        templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account"
        template = 'customMessage.htm'

    # Render the page
    template = jinja_environment.get_template(template)
    self.response.out.write(template.render(templateValues))

But we can clean up our actual work functions a little more:

def show_user(self, user):
    # Get the actual user data
    data = Person.gql("WHERE username = :nick",
                                        nick=user.nickname()).get()
    # Test if we found the user
    if data:
        return 'myAccount.htm', {
                'data' : data
        }
    else:
        return 'custom_msg.htm', {
                'custom_msg' : "The logged user is not available."
        }


Get time slots based on multiple workshops

You can simplify the creation of DAY_CHOICES using the calendar module:

DAY_CHOICES = tuple(enumerate(calendar.day_name))

this has the advantage of using the right locale, if need be.

You can reduce going back and forth between Python and your SQL backend using prefetching of objects, instead of querying each time you need something. Django offers the prefetch_related operation:

workshops = Workshop.objects.prefetch_related(
    Prefetch(
        'workshopholiday_set',
        queryset=WorkshopHoliday.objects.filter(
            holiday_date__ge=start_date,
            holiday_date__le=start_date + timezone.timedelta(days=7),
            active=True),
        to_attr='holidays_for_the_week'))

Where start_date is timezone.now().date(). This way, you get a list of every WorkshopHoliday for the upcoming week associated to the current workshop into workshop.holidays_for_the_week. You can test if the current date is in there with:

if curdate in {h.holiday_date for h in workshop.holidays_for_the_week}:
    continue

I would also advise to exchange the two for loops so you don't compute the set of holiday dates seven time for the same workshop.

curdate_dict is not necessary. You can replace

curdate_dict = {'start_time': None, 'end_time': None}

by

start_time, end_time = None, None

and remove all curdate_dict.get(…) and curdate_dict[…] = …. You just need to slots[curdate] = {'start_time': start_time, 'end_time': end_time} then, which will improve the memory management as well.

current_time.replace(hour=0, minute=0, second=0)

does nothing: the replace method returns a new datetime instance and since you’re not assigning it, you’re just wasting time.

for i in range(1, 7):

First of, i is never used: you should write _ instead to indicate that. Second, range(1, 7) produces 6 values. So you will perform your computations for today and the 5 next days. If you wished to compute your hours for a whole week, you should have written

for _ in range(7):

instead.

I also advise you to get the "counter" near that line. This is so the reader can grasp your intent more easily:

def get_slots():
    starting_time = timezone.now()
    start_date = starting_time.date()
    workshops = Workshop.objects.prefetch_related(
        Prefetch(
            'workshopholiday_set',
            queryset=WorkshopHoliday.objects.filter(
                holiday_date__ge=start_date,
                holiday_date__le=start_date + timezone.timedelta(days=7),
                active=True),
            to_attr='holidays_for_the_week'))
    slots = {}
    for day in range(7):
        current_time = starting_time + timezone.timedelta(days=day)
        …


It is possible to utilize itertools.groupby() using indexes to calculate if there is a gap:

import datetime
from datetime import timedelta
from functools import partial
from itertools import groupby
from operator import itemgetter

def is_consecutive(start_date, item):
    """A grouping key function that highlights the gaps in a list of datetimes with a 30 minute interval."""
    index, value = item
    return (start_date + index * timedelta(minutes=30)) - value

available = [
    datetime.datetime(2010, 1, 1, 9, 0),
    datetime.datetime(2010, 1, 1, 9, 30),
    datetime.datetime(2010, 1, 1, 10, 0),
    datetime.datetime(2010, 1, 1, 10, 30),
    datetime.datetime(2010, 1, 1, 13, 0),  # gap
    datetime.datetime(2010, 1, 1, 13, 30),
    datetime.datetime(2010, 1, 1, 15, 30),  # gap
    datetime.datetime(2010, 1, 1, 16, 0),
    datetime.datetime(2010, 1, 1, 16, 30)
]

start_date = available[0]

result = []
for _, group in groupby(enumerate(available), key=partial(is_consecutive, start_date)):
    current_range = list(map(itemgetter(1), group))

    result.append({
        'start': current_range[0],
        'end': current_range[-1]
    })
print(result)

Prints:

[
    {'start': datetime.datetime(2010, 1, 1, 9, 0), 'end': datetime.datetime(2010, 1, 1, 10, 30)},
    {'start': datetime.datetime(2010, 1, 1, 13, 0), 'end': datetime.datetime(2010, 1, 1, 13, 30)},
    {'start': datetime.datetime(2010, 1, 1, 15, 30), 'end': datetime.datetime(2010, 1, 1, 16, 30)}
]


In some JavaScript engines (if I remember correctly, V8) cannot optimize code inside a try-catch. So while it may be negligible in this case, it's a practice to avoid. The workaround to it is to move out the code from the try catch to a function and call that function from the try-catch instead.

Not all your cookie names appear to be in variables. Move them into variables for consistency as well as to avoid hardcoding the cookie names everywhere.

Lastly, ES6 modules are by default run in strict mode. So no need to define 'use strict';.

The code can be simplified into the following. If you just separate the IO from the data manipulation, you can easily see patterns in the code which you can simplify.

import Cookie from 'js-cookie';
import  _ from '../helpers';

module.exports = (event) => {
  const uidCookieName = 'sp';
  const pidCookieName = 'pID';
  const sidCookieName = 'sID';
  const suCookieName  = 'su';

  const sID = Cookie.get(sidCookieName);
  const uID = Cookie.get(uidCookieName) || _.uuid();
  const pID = Cookie.get(pidCookieName) || _.uuid();
  const su  = Cookie.get(suCookieName)  || _.uuid();

  const uNw = !!Cookie.get(uidCookieName);
  const uUq = su ? 0 : 1;

  Cookie.set(uidCookieName, uID);
  Cookie.set(pidCookieName, pID);
  Cookie.set(suCookieName, su, { expires: 30 });

  return { uID, sID, pID, uNw, uUq };
}


Coalescing lvalue references to std-optionals

So ideally you want to write something like:

template <typename... Ts>
constepxr auto coalesce(std::optional<Ts>&... xs)
{
   return (xs || ...);
}

But the issue here is of course that it will convert the optionals to bool before applying the boolean or-operator. You could however cast it to a type that does provide the right semantics for the boolean or-operator to do the thing you want:

template <typename T>
struct coalescable {
    T &x;
    coalescable(T &x_): x(x_) {}
    constexpr const coalescable &operator||(const coalescable &other) {
        return x.has_value() ? *this : other;
    }
};

And then use that in the fold expression:

template <typename... Ts>
constepxr auto coalesce(std::optional<Ts>&... xs)
{
   return (coalescable(xs) || ...).x;
}


As dfhwze and Roland already pointed out, a hash alone is not sufficient to determine whether two things are equal, so you still need to do a string comparison afterwards if the hashes match. Otherwise you will get wrong results from time to time. Not to mention the effect of hash randomization between different application runs...

The idea behind Rabin-Karp's use of hashes is to replace costly string comparisons with cheap hash comparisons. But in your case, the cost of creating a substring and calculating its hash (which involves some calculations for every character) is often greater than doing a direct string comparison (which can bail out at the first difference).

As the Wikipedia article that you linked to says, you'll want to use a rolling hash, a hashing algorithm that allows you to calculate the hash of the next substring with just a few operations, regardless of how long that substring is.

Also, as far as I can tell, storing string.Length in a local variable doesn't offer any performance improvements. It does make the code slightly less readable though, in my opinion.


Almost everything is perfect. Some notes:

Do use var to avoid repeating in cases like Mock<IUnitOfWork> unitOfWorkMock = new Mock<IUnitOfWork>()
Move mocks initialisation and wiring up to SetUp method to avoid copy-pasting in different test methods, and leave only actual setups that provide test data in test method
It's hard to unit test the code that uses DateTime.Now. For example your test may fail when running near midnight (since you call DateTime.Now several times, and subsequent calls may return the next day). I would suggest to add the UtcNow property to your IDateService and always use it instead of DateTime.Now (I prefer to force using UTC time since it forces you to think about time zones). Then, most likely you won't need methods like GetFirstDateOfWeek in IDateService (if they depend on inputs only), they could be just extension methods to DateTime.
You don't need to verify that GetFirstDateOfWeek and GetLastDateOfWeek were called, just make sure that result matches expected value. The reason is because the call to those methods does not guarantee that returned values were used correctly. And when all tests pass without those calls - it only shows that you should add more tests to verify that returned values were used properly

As a result you'll have something like this:

[Test]
public void WhenWeekStartOnSunday...ShouldReturnSomething
{
    const int schoolyearId = 1;
    var currentDate = new DateTime(2010, 1, 1).ToUniversalTime();
    var periods = new [] {...}; //specify test periods here

    //Arrange
    _schoolyearRepositoryMock.Setup(s => s.GetById(schoolyearId)).Returns(new Schoolyear() { FirstDayOfWeek = DayOfWeek.Sunday });
    _dateServiceMock.Setup(s => s.UtcNow).Returns(currentDate);
    _lessonplannerRepoMock.Setup(lp => lp.GetWeeklyPeriods(schoolyearId, new DateTime(2010, 1, 1),
            new DateTime(2010, 1, 5))) //specify the dates expected according to "currentDate" value.
        .Returns(periods);

    var service = new LessonplannerService(_unitOfWorkMock.Object, _dateServiceMock.Object);

    // Act
    LessonplannerRequest request = service.GetWeeklyLessonplanner(schoolyearId);

    // Assert
    Assert.That(request.Periods, Is.SameAs(periods));
    Assert.That(request.Weeks, Is.Empty); //verify here expected list of weeks according to logic of the method
}


Searching based on a query string and returning JSON ActionResult

In following query

var suggestions = Db.Entities.Where(x => x.Name.Contains(search.Name)
                              && x.EntityId != accountId
                              && !String.IsNullOrEmpty(x.Group.Label))
                 .ToList()
                 .Select(item => new { id = item.GroupId, text = item.Group.Label });

You shouldn't call ToList(). Read this answer from a question on StackOverflow. This is the essential part:

  For example, in an Entity Framework query we can only use a restricted number of methods. So if, for example, we need to use one of our own methods in a query we would typically write something like

   var query = context.Observations.Select(o => o.Id)
               .AsEnumerable().Select(x => MySuperSmartMethod(x))

  ToList – which converts an IEnumerable to a List – is often used for this purpose as well. The advantage of using AsEnumerable vs. ToList is that AsEnumerable does not execute the query. AsEnumerable preserves deferred execution and does not build an often useless intermediate list.

  On the other hand, when forced execution of a LINQ query is desired, ToList can be a way to do that.

No need to check twice for the query to see if it is empty. Your code would be better like this:

if (query == "")
{
    if (accountId == null)
    {
        //return Json
    }
    else
    {
        //return some other Json
    }
}

You can improve the performance of your LinQ query by building it correctly. First check for the EntityId != accountId, then !String.IsNullOrEmpty(x.Group.Label) and last for x.Name.Contains(search.Name):

var suggestions = Db.Entities.Where(x => x.EntityId != accountId
                              && !String.IsNullOrEmpty(x.Group.Label)
                              && x.Name.Contains(search.Name))
                 .AsEnumerable()
                 .Select(item => new { id = item.GroupId, text = item.Group.Label });

Notice that I changed ToList to AsEnumerable.

Variable names like list and search are not meaningful. Give clear names to your variables that kind of represent what they are holding.

var list = Db.Groups.Where(...);

would become:

var groups = Db.Groups.Where(...);


"Silly program" for moving the mouse and doing other things

Please do not use using namespace std (read this).

Convert magic numbers like 1440 and 900 to global constants with meaningful names. I would do the same for string literals like \\explorer.exe and taskmgr.exe, but maybe that's just me

Your formatting is not consistent. Sometimes you assign variables like pEntry.dwSize = ..., with spaces around =, and sometimes like mouseX= , space only on one side. I suggest to put spaces on both sides, and to be consistent about it.

I would put these two assignments on separate lines for clarity:

mouseX= rand() % 1440; mouseY= rand() % 900;


Determining whether a string is transformable into another by repetitively increasing its prefixes alphabetically

Code review

In general, the code looks nice and follows consistent styles.  Some small observations:

Missing #include <string>.
Avoid std::endl when \n suffices.  std::endl flushes the buffer, while \n does not.  Unnecessary flushing can cause performance degradation.  See std::endl vs \n.  Use

std::cout << "YES\n";

instead of

std::cout << "YES" << std::endl;

unless flushing is a requirement from the website (I hope not).
Since we are depending on lowercase letters being continuously encoded anyway, 'B' - 'A' is just 1.  And A[i] += 1 becomes ++A[i].

Better algorithm

That said, the logic of the code is overly convoluted.  The many levels of nested control statements make it hard to follow the code.  There is a much simpler algorithm to do it: to determine whether A is transformable into B,

take the differences between the corresponding positions B[i] - A[i];
form a sequence out of these differences;
append the sequence by 0 (to prevent cases like bbbbb => aaaaa);
test if this sequence is sorted in non-ascending order.

For example:

for A = "abcde", B = "ccdde", the sequence of differences is 21100, so the transformation is possible (abcde => bcdde => ccdde);
for A = "abcde", B = "bbcce", the sequence of differences is 10010, so the transformation is impossible (try it).

Here's (roughly) how I would put everything together:

#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>

bool transformable(std::string_view a, std::string_view b)
{
    if (a.size() != b.size()) {
        return false;
    }
    std::vector<int> diff_sequence(a.size() + 1);
    std::transform(b.begin(), b.end(), a.begin(), diff_sequence.begin(), std::minus<>{});
    diff_sequence.back() = 0;
    return std::is_sorted(diff_sequence.begin(), diff_sequence.end(), std::greater<>{});
}

int main()
{
    std::string A;
    std::string B;

    std::cin >> A >> B;

    if (transformable(A, B)) {
        std::cout << "YES\n";
    } else {
        std::cout << "NO\n";
    }
}

(live demo)

(Replace std::string_view with const std::string& and remove the #include <string_view> if C++17 is not available, which IIRC is the case with competitive programming sites.)

The transformable function can be simplified with the range-v3 library:

namespace views = ranges::views;

bool transformable(std::string_view a, std::string_view b)
{
    return ranges::is_sorted(
        views::concat(
            views::transform(b, a, std::minus<>{}),
            views::single(0)
        ), std::greater<>{});
}

(live demo)


Perform instruction in loop every time except the last time?

I presume lines is a Collection of some sort. One option that has slightly less of a smell (although it still is odoriferous), is to use an iterator, which will essentially do the same work, but will be more readable:

for (Iterator<String> it = lines.iterator(); it.hasNext();) {
    writer.write(it.next());
    if (it.hasNext()) {
        writer.newline();
    }
}

As I say, all this does is make it more readable....

Other options are to duplicate the write - once in the loop, and then the last one outside the loop:

if (!lines.isEmpty()) {
    int limit = lines.size() - 1;
    for (int i = 0; i < limit; i++) {
        ....
    }
    writer.write(lines.get(limit));
}

EDIT: @tomdemuyt suggested reversing the newline to happen only after the first line as follows:

if (!lines.isEmpty()) {
    writer.write(lines.get(0));
    // start index at 1 instead of 0.
    for (int i = 1; i < lines.size(); i++) {
        writer.newline();
        writer.write(lines.get(limit));
    }
}


The code looks fine to me. Just a couple minor points:

Why do you change the div's position to relative? If the function is called on a div with absolute positioning, it would mess up the layout. And you should revert the CSS changes on RemoveMask() to what they were when Mask() was called because the div's content might depend on a certain overflow value.
If the div changes size while masked, the image will no longer be horizontally centered. I would suggest using CSS instead of JS to center it:

.MaskContent {
  background: none;
  position: absolute;
  width: 32px;
  height: 32px;
  top: 30%;
  left: 50%;
  margin-left: -16px;
  z-index: 5;
}

Your mask background currently only supports webkit browsers; you should add the CSS3 variations for the other browsers.


Given a sorted dictionary of an alien language, find order of characters

words = ["baa", "abcd", "abca", "cab", "cad"]

I don't believe you ever mutate words so you should make it constant by making it a tuple:

words = ("baa", "abcd", "abca", "cab", "cad")

This:

words = ["baa", "abcd", "abca", "cab", "cad"]
chars = collections.OrderedDict()
for word in words:
    for c in word:
        chars[c] = True

    nodes_map = collections.defaultdict(list)
    for i, word in enumerate(words[:-1]):
        nxt = words[i+1]
        for a, b in zip(word, nxt):
            if a != b:
                nodes_map[a] += [b]
                break
    for i in topological_sort(nodes_map, chars):
        print i,

Should probably wrapped into a "main function". Furthermore, to keep stuff in the "main scope" I highly recomend you actually make a main function. So instead of just:

if __name__ == '__main__':
    words = ("baa", "abcd", "abca", "cab", "cad")
    chars = collections.OrderedDict()
    ...

You should do:

def main():
    words = ("baa", "abcd", "abca", "cab", "cad")
    nodes_map = collections.defaultdict(list)
    for i, word in enumerate(words[:-1]):
        nxt = words[i+1]
        for a, b in zip(word, nxt):
            if a != b:
                nodes_map[a] += [b]
                break
    for i in topological_sort(nodes_map, chars):
         print i,

if __name__ == '__main__':
    main()

Instead of using a list to store results change it to a dequeue by making it results = collection.dequeue(). This gives you the appendleft method which adds stuff to the beginning of the "list". This means you don't need to return reversed(results), just return results.


Count distinct primes, discarding palindromes, in under 2 seconds

There are a few things you could optimize:

If you (or the grading server?) are running this on Python 2.x, you should definitely use xrange instead of range (about 2 seconds on my system)
In your prime sieve, you have to check the multiples only if the current number is a prime (down to 1s); also, instead of multiplying, count by multiples of is
use a regular array instead of a dictionary in the sieve (0.8s)
don't do that string-conversion and reversing more often than necessary; also instead of implementing your own binary search, just use sets for quick lookup (0.4s)

My version (updated):

def primes(limit):
    numbers = [0, 0] + [1] * (limit-2)
    for i in xrange(2, limit):
        if numbers[i]:
            for k in xrange(i**2, limit, i):
                numbers[k] = 0
    return set(i for i, e in enumerate(numbers) if e)

ps = primes(LIMIT)
final = set()
for p in ps:
    q = int(str(p)[::-1])
    if p != q and q in ps and q not in final:
        final.add(p)

Not sure whether this get's the running time down from 16s to 2s in your case, but it might be a start. As a desperate measure, you could decrease LIMIT -- better to find not quite as many than to timeout.


I'm not very familiar with cURL either, but looking at the documentation I noticed a curl_setopt_array() function that may be worth looking into.

$options = array(
    CURLOPT_HEADER => FALSE,
    CURLOPT_URL =>  $url,
    //etc...
);

curl_setopt_array( $curl_handle, $options );

Looking at the documentation for curl_exec() shows that the only time its output will be FALSE is on failure. The only time it is really necessary to compare a value explicitly with a boolean is if that value will at some point be a boolean and at all other times won't, but may be mistaken for it (0, '', 'false', etc...). However, at this point you would then use absolute equality comparison instead of a loose one. For instance, the below example will output "asdf", "false", '', and 0 from the first if statement, but the second and third if statements will only ever output "asdf". This is because the first if statement uses an absolute, or strict, comparison to the boolean. The third if statement shows a cleaner way of doing the second. Any variable you can loosely compare with a boolean, can loosely be used as a boolean, so there's no need to type out the actual comparison. I would use that last if statement because its not likely you want to create an empty file, and unless you have a file with only a "false" value in it, then you are not likely to notice the difference.

$buffer = array( FALSE, 'asdf', 'false', '', 0 );

foreach( $buffer AS $test ) {
    if( $test !== FALSE ) {//absolute
        var_dump( $test );
    }
    if( $test != FALSE ) {//loose
        var_dump( $test );
    }
    if( $test ) {//another way of writing loose
        var_dump( $test )
    }
}

The only other thing I would suggest here is that you verify that your $xml_file exists before trying to write to it.

if( $buffer && is_file( $xml_path . $xml_file ) ) {


I would do this:

function TMyObject.GetCursor: TCursor;
begin
  if CanDragX and CanDragY then
    Result := crSizeAll
  else if CanDragX then
    Result := crSizeWE
  else if CanDragY then
    Result := crSizeNS
  else
    if CanClick then
      Result := crHandPoint
    else
      Result := crArrow;
end;

But really it is a matter of style and what is most readable to you (and the person who will maintain it).


Class with multiple parameters as the object of a WeakReference

What about this

private static class AddBooksToDatabase extends AsyncTask<String, String, String> {

  private String TAG = "TownFragment";

  private WeakReference<Context> mContextRef;
  private WeakReference<TextView> mInfoTextRef;
  private WeakReference<String> mTownNameRef;
  private WeakReference<File> mFileRef;
  private WeakReference<WaveLoadingView> mWaveViewRef;

  public AddBooksToDatabase(Context context, TextView infoText, String townName, File file, WaveLoadingView waveView) {
    mContextRef = new WeakReference<>(context);
    mInfoTextRef = new WeakReference<>(infoText);
    mTownNameRef = new WeakReference<>(townName);
    mFileRef = new WeakReference<>(file);
    mWaveViewRef = new WeakReference<>(waveView);
  }

  @Override
  protected String doInBackground(String... strings) {
    TownHelper helper = TownHelper.getInstance(mContextRef, dbName);
    SQLiteDatabase database = helper.getWritableDatabase();
    int booksSize = getFilesInFolder(mFileRef).size();
    //Stuffs
    return null;
  }

  @Override
  protected void onPreExecute() {
    WaveLoadingView waveView = mWaveViewRef.get();
    if(waveView != null) {
      waveView.setVisibility(View.VISIBLE);
    }
  }

  @Override
  protected void onPostExecute(String s) {
    WaveLoadingView waveView = mWaveViewRef.get();
    if(waveView != null) {
      waveView.setVisibility(View.GONE);
    }
  }

  @Override
  protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    Log.d(TAG, "Progress report = " + values[0]);
    TextView infoText = mInfoTextRef.get();
    infoText.setText(values[0]);
  }

  @Override
  protected void onCancelled() {
    cancel(true);
  }
}

Without seeing the surrounding code or understanding too much about it's purpose/function, here is how I would change the code

private static class AddBooksToDatabase extends AsyncTask<String, String, String> {

  private String TAG = "TownFragment";

  private WeakReference<Context> mContextRef;

  private String mTownName;
  private File mFile;

  private Dialog mProgressDialog;

  private TextView mInfoText;
  private WaveLoadingView mWaveView;

  /*
  * A constructor/method should rarely exceed 3 parameters.
  * */
  public AddBooksToDatabase(Context context, String townName, File booksFolder) throws IOException {
    /*
    * Since the file parameter must be a directory add in this
    * check as early as possible and throw a checked exception
    * which the caller must handle if it fails.
    * */
    if(!booksFolder.isDirectory()) {
      throw new IOException("the file " + booksFolder.getName() + " is not a directory");
    }
    /*
    * Holding a WeakReference to the Context because
    * the AsyncTask should not outlive the Context.
    * */
    mContextRef = new WeakReference<>(context);

    mTownName = townName;
    mFile = booksFolder;

    /*
    * The progress views are initialised inside the
    * AsyncTask, no need to pass them in as arguments.
    * */
    mInfoText = new TextView(context);
    mWaveView = new WaveLoadingView(context);

    /*
    * Create a dialog to display the progress views.
    * */
    LinearLayout progressDialogView = new LinearLayout(context);
    progressDialogView.setOrientation(LinearLayout.VERTICAL);
    progressDialogView.addView(mInfoText);
    progressDialogView.addView(mWaveView);
    mProgressDialog = new AlertDialog.Builder(context)
        .setTitle("Adding books")
        .setView(progressDialogView)
        .create();
  }

  @Override
  protected void onPreExecute() {
    /*
    * Display the progress dialog
    * when the task starts executing.
    * */
    mProgressDialog.show();
  }

  @Override
  protected String doInBackground(String... strings) {
    final Context context = mContextRef.get();
    TownHelper helper = TownHelper.getInstance(context, dbName);
    SQLiteDatabase database = helper.getWritableDatabase();
    int booksSize = getFilesInFolder(mFile).size();
    //Stuffs
    return null;
  }

  @Override
  protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    Log.d(TAG, "Progress report = " + values[0]);
    mInfoText.setText(values[0]);
  }

  @Override
  protected void onPostExecute(String s) {
    /*
    * Dismiss the progress dialog
    * when the task finishes executing.
    * */
    mProgressDialog.dismiss();
  }

  @Override
  protected void onCancelled() {
    cancel(true);
  }

}


Setting all possible combinations of values

Based on how you store objects at indices determined by the init values, and not stored in sequential order, I'm going to guess that you have a function somewhere that takes an object's index and returns the matching values of a,b,c,d,e.

Let's say it's std::tuple<int,int,int,int.int> get_values(int obj_index);

You could leverage that same function to clean up the generating loop:

for(int i=0; i < 10*10*10*10*10; ++i) {
  auto values = get_values(i);
  objectList[i].val1 = ((std::get<0>(values) - 5) * magnitude) + bestVal1;
  objectList[i].val2 = ((std::get<1>(values) - 5) * magnitude) + bestVal2;
  objectList[i].val3 = ((std::get<2>(values) - 5) * magnitude) + bestVal3;
  objectList[i].val4 = ((std::get<3>(values) - 5) * magnitude) + bestVal4;
  objectList[i].val5 = ((std::get<4>(values) - 5) * magnitude) + bestVal5;
}

If you don't have such a function, then indexing the objects in the way you do makes no sense, and you should just be storing them in order of generation.

Apart from that, my other recommendations would be too dependant on the context.

For instance, I would look for a way to not have to store the entire table of objects, and implement the evaluation algorithm in a way that at most a few objects have to be in existence at the same time.

I would also consider that brute-forcing an optimization problem like this is generally a last resort, so I would probably look for tackling this with something like a gradient descent if possible.


Safely accepting a known SSL certificate with a different host name

There are a few items inhere I would suggest can be improved (assuming the security aspects of the code are valid - i.e. legal disclaimer about 'safe' and SSL means speak to someone who's more of a security expert than me).

First, I assume you are using the apache-commons based HttpClient code.... this is fine, but it would have been useful to show the import statements ;-).

Regardless. There are three things I would change.

First, whenever you do an anonymous class implementation and it has more than 1 method that needs to be overridden, then I recommend that you create a full class implementation for it. In this case, your code should have a (perhaps nested) class that implements the

private static final class AlternateHostnameVerifier implements X509HostnameVerifier {
    ....
}

then your code becomes:

HttpClient httpclient = new DefaultHttpClient();
SSLSocketFactory ssf = SSLSocketFactory.getSocketFactory();
ssf.setHostnameVerifier(new AlternateHostnameVerifier());
httpclient.getConnectionManager().getSchemeRegistry().unregister( "https" );
httpclient.getConnectionManager().getSchemeRegistry().register( new Scheme( "https", ssf, 443 ) );

This is a much better way to show the critical logic of your program, and still make it readable.

Next up, in your new AlternateHostnameVerifier class, I would recommend you implement all the interface methods fully. Leaving two of the methods as stub methods is only a short-term solution. In the future the apache-commons implementation may change and call one of the other verify methods, and then you have a sudden, unexplained bug. Specifically throwing a UnsupportedOperationException is a much better alternative than leaving it blank.

Finally, I have a preference for methods that can to simply 'return' when they succeed rather than trying to break out of loops and keep track of variables outside of the loops.

In this case, you have foundHost which tracks the state. you can eliminate this variable if you just 'return' each time you set it to true, and otherwise always throw the exception.

So, you can rewrite the code as:

@Override
public void verify( String host, SSLSocket ssl ) throws IOException {
  for( javax.security.cert.X509Certificate cert : ssl.getSession().getPeerCertificateChain() ) {
     String[] tokens = cert.getSubjectDN().getName().split( "," );
     for( String token : tokens ) {
        String[] keyVal = token.split( "=" , 2);

        if( keyVal.length > 1 && keyVal[0].equals( "CN" ) ) {
           if (keyVal[1].equals( host ) || keyVal[1].equals( context.getString( R.string.CertHostName ) )) {
               // our CN matches the Android's certificate host.
               return;
           }
        }
     }
  }
  throw new IOException( "Mismatched host in SSL certificate" );
}