Coding conventions

Have at least one empty line after all #includes.
Have one space character before and after every binary operator. For example, a + 1 instead of a+1. That makes your code easier to read.
Have one space after each for keyword: not for(i=1;i<10;i++), but rather  for (i = 1; i < 10; i++). (Same applies to if.)
Fix your indentation:

for(j=low;j<high;j++)
  {
      if(a[j]<a[high])
      {
         i++;
         swap1(&a[i],&a[j]);
      }
  }

to

for(j=low;j<high;j++)
{
    if(a[j]<a[high])
    {
        i++;
        swap1(&a[i], &a[j]);
    }
}

Instead of writing &a[index] you can write simply a + index.
Whenever printing a simple (non-formated) standard output, use puts instead of printf. (Also, note that puts automatically adds the new line character after the argument string.)

All the above points are relevant to readability of your source code.

Summa summarum

All in all, I had this in mind:

#include<stdio.h>

void quicksort(int*, int, int);
int partition(int*, int, int);
void swap(int*, int*);

int main()
{
    int low = 0;
    int length;
    int i;
    int a[100];
    int high;

    puts("Enter the length of array:");
    scanf("%d", &length);

    high = length - 1;

    puts("Enter the array elements:");

    for (i = 0; i <= high; i++)
    {
        scanf("%d", &a[i]);
    }

    quicksort(a, low, high);

    puts("The sorted array:");

    for (i = low; i <= high; i++)
    {
        printf("%d ",a[i]);
    }

    puts("");
    return 0;
}

void quicksort(int a[],int low,int high)
{
    int p;

    if (low < high)
    {
        p = partition(a, low, high);
        quicksort(a, low, p - 1);
        quicksort(a, p + 1, high);
    }
}

int partition(int* a, int low, int high)
{
    int pivot = a[high];
    int i = low;
    int j;

    for (j = low; j < high; ++j)
    {
        if (a[j] <= pivot)
        {
            swap(a + i++, a + j);
        }
    }

    swap(a + i, a + high);
    return i;
}

void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

Hope that helps.


I have very little to say, maybe others will have more.

if (self.count > self.concurrency) {
    self.queue.push(task);
}

if (self.count <= self.concurrency) {
    task(done);
}

Why not if / else? At least it'll be clear it's one or the other.

this.queue.shift() is cleaner than this.queue.splice(0, 1)[0].

There's also a nitpick about self.count = self.count + 1; where += 1 could be used instead, but it really depends on the coding style.

About the callbacks, you could move to the newer Promise which is part of ECMAScript 2015.

ConcurrencyQueue.prototype.enqueue = function (task) {
    this.count += 1;

    if (this.count > this.concurrency) {
        this.queue.push(task);
    } else {
        this.execute(task);
    }
};

ConcurrencyQueue.prototype.execute = function(task) {
    var p = new Promise(task);

    /* `() => {` is a simpler notation for `function() {` in recent JS,
        but `this` refers to the encompassing `this` */
    var done = () => {
        this.count -= 1;
        if (this.queue.length) {
            this.execute(this.queue.shift());
        }
    };

    /* First argument is in case of success, second in case of errors */
    p.then(done, done);
}

jsFiddle


You can improve the performance of the inner divisibility test by using std::div to do the division and modulo operations in one step. The following should work:

    for (;;) {
        auto r = std::div(n, p);
        if (r.rem != 0) {
            break;
        }
        n = r.quot;
        base_factors.push_back(p);
    }

The return value of std::div is a type such as std::lldiv_t (the exact return type ultimately depends on the template type parameter T).


Finding the maximum number of id's among all weeks available

Instead of iterating through each possible week and filtering your dataframe, you should use df.groupby and work from there using convenience methods on the results:

df.groupby('week').id.nunique().max()


Issue 1: Is there a way to avoid the back and forth converting between datetime and string?

There is, but it's not gonna be easy.
You could inject data into the template as JavaScript code.
That way the page will have the dates in native format.
To make that work,
you would have to stop injecting the data as HTML code,
and use JavaScript to generate it based on the injected dates in native format.

But unless you have large amounts of data,
you might not need this.
The conversions back and forth between datetime and string might not be significant.

  Issue 2: I would like the code to stay DRY, so any ideas on how to make the function be able to handle both datetime.date and datetime.time objects would also be very welcome.

Easy.
You could inject the filtering functionality.
In particular,
the most important part of your implementation is extracting a value to compare from the data.
This kind of function is often called key.
You could define such function to convert the string to time:

var time_key = function(s) {
    var parts = s.split(':');
    return new Date(0, 0, 0, parts[0], parts[1]);
}

Then you could inject this as the key parameter to filter:

function filter(id, column_id, key) {
    var i, value;
    var table = document.getElementById("myTable");
    var tr = table.getElementsByTagName("tr");
    var ref = key(document.getElementById(id).value);

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[column_id];
        if (td) {
            value = key(td.innerHTML.split(':'));
            tr[i].style.display = value < ref ? "none" : "";
        }
    }
}


Hacking Ruby Hash: Fastest #to_struct method

Use OpenHash and Ruby >= 2.3.0

Starting with MRI 2.3.0, your benchmark using OpenHash gets fast.  Very fast:

ruby-2.2.5: ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-linux]
       user     system      total        real
#to_struct  1.780000   0.000000   1.780000 (  1.774490)
Struct  9.100000   0.000000   9.100000 (  9.099619)
OpenStruct  7.910000   0.000000   7.910000 (  7.911342)

ruby-2.3.0: ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
       user     system      total        real
#to_struct  1.700000   0.000000   1.700000 (  1.695587)
Struct  7.660000   0.000000   7.660000 (  7.660869)
OpenStruct  0.650000   0.000000   0.650000 (  0.658817)

With the latest MRI, Your #to_struct method gets a bit of a speed boost as well.

ruby-2.4.1: ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
       user     system      total        real
#to_struct  1.460000   0.000000   1.460000 (  1.459063)
Struct  7.420000   0.000000   7.420000 (  7.416505)
OpenStruct  0.660000   0.000000   0.660000 (  0.658009)

So if you can, use Ruby >= ruby 2.3.0, and use OpenHash.

How to make #to_struct faster

I made the following changes for performance:

Eliminate the mapping of hash keys using #downcase.
Use #values instead of #values_at (values are always the same order as keys).  See https://stackoverflow.com/a/31425274/238886

and these for clarity:

Eliminate the temporary for self.keys
DRY the creation of the struct instance
Removed self references.

With these changes, the code is:

class Hash
  def new_to_struct
    klass_name = keys.map(&:to_s).sort.join.capitalize
    klass = begin
              Kernel.const_get("Struct::" + klass_name)
            rescue NameError
              Struct.new(klass_name, *keys)
            end
    klass.new(*values)
  end
end

and the benchmark (run against ruby-2.4.1):

       user     system      total        real
#to_struct  1.410000   0.000000   1.410000 (  1.403908)
#new_to_struct  0.760000   0.000000   0.760000 (  0.757548)
Struct  7.060000   0.010000   7.070000 (  7.075619)
OpenStruct  0.650000   0.000000   0.650000 (  0.649057)

These changes get to_struct close to OpenStruct, but still not as fast.


List of word to list of index in a vocabulary

When using NumPy, stick to NumPy functions where possible instead of going via pure Python and back again (which is usually slower). So instead of getting the unique elements of an array by writing np.array(list(set(...))), call numpy.unique.
The expression np.argwhere(vocs[j]==x[i,j]) has to search the whole vocabulary for the word x[i,j], and this has to be done for every feature in every sample. This means that if there are \$s\$ samples and \$f\$ features, and each feature has \$w = O(s)\$ words, the overall runtime is proportional to \$sfw = O(s^2f)\$. That is, it's quadratic in the number of samples. This is why it takes so long.

To avoid this, we need to construct, for each feature, an inverse mapping from words in the samples to their indexes in the vocabulary. How do we construct such inverse mappings? Well, looking at the numpy.unique documentation, we find that it takes a keyword argument:

  return_inverse : bool, optional

  If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct ar.

These inverse arrays are exactly what you need, and so your code becomes:

vocs, inverses = zip(*(np.unique(feature, return_inverse=True) for feature in x.T))
x_new = np.vstack(inverses).T


Is there a better way to flatten out a multidimensional list?

Without many details, maybe the following can help you:

>>> import itertools
>>> list_of_lists = [['item_1'], ['item_2', 'item_3'], ['item_4', 'item_5', 'item_6']]
>>> chain = list(itertools.chain(*list_of_lists))
>>> print chain
['item_1', 'item_2', 'item_3', 'item_4', 'item_5', 'item_6']

Take a look at this question, there are some answers that might help you.


Approximately matching strings to elements in an array

Code Style Review:

Use of Redundant variables: I cannot find any use for max in your
script. Remove it
Better naming: jw could be better described as jw_score. Max is
built_in name, don't use it.
Unnecessary enumerate. You are not using index in inner loop. Remove
enumerate.
I am assuming confidence is global scope. Bad practice. Pass
confidence value as argument. If you must use confidence as global
constant, declare it as CONFIDENCE (caps indicate constant)
Since you are inserting zero as initial value for temp_list there are better ways to achieve that instead of appending zero in loop.
Use item_data while iterating data, and vice-versa. Your naming
convention right now is confusing

Code Design Review

I am having hard time understanding what you wanted to return. Right now, if any of strings for data matches target, your temp_list will have a value for it. But it will have value for "last_matched" only.

If you only care about any good match, then as soon as any value match, break out from inner loop, and your average running time should reduce drastically:

def get_jw_match(data, target, confidence):
    """Uses the jaro-winkler algorithm to match strings(names) from the   target(the set from which you want to find matches) to the data(the set for which you are trying to find matches."""
    score_list = [0] * len(target)
    for i, item_target in enumerate(target):
        for item_data in data:
            jw_score = jellyfish.jaro_winkler(item_data, item_target)
            if (jw_score > confidence):
                score_list[i] = jw_score
                break
    return score_list

Now you would know for which elements in target you have good match, but you don't know any element in data for which you have good match. For that, instead of assigning score, you can assign index for data.
Also, you can then ditch list, and use dictionaries:

def get_jw_match(data, target, confidence):
    """Uses the jaro-winkler algorithm to match strings(names) from the   target(the set from which you want to find matches) to the data(the set for which you are trying to find matches."""
    score_dict = dict()
    for i, item_target in enumerate(target):
        for j, item_data in enumerate(data):
            jw_score = jellyfish.jaro_winkler(item_data, item_target)
            if (jw_score > confidence):
                score_dict[i] = j
                break
    return score_dict

Advantage of this is that you can create reverse dict also.
Which also means, that you should be able to swap inner-outer loops reducing time further. (In general, use inner loop for bigger data, when it short circuit, you save much more time)

If I think, there might be further time-reduction optimizations, but for practical purposes, this would shorten your average running time by magnitude.


You've got a random string inside your function, it is unhelpful, you should remove that. If, however, you meant to make a comment, you should have used the comment sign (#).

For the existence of methods, combining dir and if .. in is inneficient as lists lookups are \$\mathcal{O}(n)\$ but attribute access is usually done through an instance's __dict__. You have two possibilities: either you execute it nonetheless and handle the AttributeError if it didn't exist, or use the getattr function to retrieve the method and then you execute it. The advantages of the latter being that:

You can easily encapsulate that behaviour in a function;
You can use the third parameter of getattr to provide a default value in case the attribute doesn't exist.

Something like this should be very generic, remove functionalities as you don't need them:

def do_nothing(*args, **kwargs):
    pass

def execute_method(name, instance, *args, **kwargs):
    method = getattr(name, instance, do_nothing)
    return method(*args, **kwargs)

Going through the rest of the code, you may also allow to pass the names of the files as parameters.

Proposed improvements look like:

FILES_TYPES = [
    RubricaManager,
    RectifiedRubricaManager,
    RectificationSpreadsheetManager,
    GPSManager,
]
METHODS = [
    'load_data',
    'spreadsheet_to_array',
    'headers_array',
    'get_used_indexes',
    'remove_duplicity_by_timestamp',
    'array_to_dictionary',
]

def do_nothing(*args, **kwargs):
    pass

def execute_method(name, instance, *args, **kwargs):
    method = getattr(name, instance, do_nothing)
    return method(*args, **kwargs)

def main(filenames=('File1.xlsx', 'File2.xlsx', 'File3.xlsx', 'File4.xlsx')):
    for filename, cls in zip(filenames, FILES_TYPES):
        spreadsheet = cls(filename)
        for method_name in METHODS:
            execute_method(method_name, speadsheet)


First, I think making it a singleton would be a mistake (singleton usually is). At best it would be extra work with zero benefit. At worst, it's a handicap, such as when/if you decide to support two top-level windows with independent settings for each.

Second, I think I'd add a Boolean named dirty (or something similar). When you set the value, dirty is set to true. When you save the value, you check if dirty is true, and only write out the value if it is (then you set dirty to false).

Personally, I'd probably change it from a static class named ProcessPath to a normal class named (something like) config_string, with an instance for ProcessPath, and a the possibility for other instances holding other strings. To do that, you'd pass Settings.Default.ProcessPath as a parameter when you construct the object.


Elegant and efficient are different things.

SimpleDateFormat instances are not thread safe. It is common in my code to have a few utility classes, and one method I often have on the utility class is:

private static final ThreadLocal<SimpleDateFormat> localDateFormat = new ThreadLocal<SimpleDateFormat>() {

    @Override
    protected SimpleDateFormat initialValue() {
             return new SimpleDateFormat(....);
    }

};

public static SimpleDateFormat getDateFormatter() {
    return localDateFormat.get();
}

That way, anyone calling getDateFormatter() gets an instance of the standard formatter for my system, and it is local to the current thread. I don't let them 'hang around', so you can't assign them to class fields, etc.

The benefit is that there's at most one instance per thread, it is thread safe (if you don't do silly things with it), and it is neat:

public void log(String message) {
    logTextArea.append(String.format("%s : %s%n",
           Utils.getDateFormat().format(new Date()), message));
}

Unfortunately, I don't think you have taken this far enough. You need another utility method like:

public static String formatLogMessage(String message) {
    return String.format("%s : %s%n",
           Utils.getDateFormat().format(new Date()), message);
}

and then all your various places that modify things like this can reuse the code:

public void log(String message) {
    logTextArea.append(Utils.formatLogMesssage(message));
}

Update: I somewhat misread your specific question, and in response to your comment:

creating a new short-term new Date() is not perfect, but is still very fast (it will be cycled out by the garbage collector very quickly, and not impact that very much at all). There are perhaps better ways though...
I don't use the commons library, so was not aware that the FastDateFormat class was thread-safe (it probably does what I suggest above), but, at the same time, the extra log-method is a good idea because it brings all the different log places in to one spot so you can change formats, etc. with just one changed line of code.

Additionally, if you are concerned about the actual performance of the new Date(), (and if you actually read the full Javadoc of the FastDateFormat class you sent me... ;-) you can replace that one method:

public static String formatLogMessage(String message) {
    return String.format("%s : %s%n",
           Utils.getDateFormat().format(new Date()), message);
}

with:

public static String formatLogMessage(String message) {
    return String.format("%s : %s%n",
           DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(System.currentTimeMillis()), message);
}


Return nil after loop and also in unless block in Ruby

Ruby has a detect method, so your entire method can be replaced with
members.detect { |member| member.name == member_name }

As an aside, each works fine for empty arrays, hence the empty? check you have is completely unnecessary even if you keep the explicit loop.


Recursive calculation of second order derivative

Recommendations:

Your output files are delimited by both spaces and tabs, which is weird.  You probably want to use tabs only.
There are a couple of points related to floating-point handling that I think deserve commenting:

Evaluating func(0.0) has a side effect of setting some floating-point error flags.
You actually intend to step x by Δx=0.01 between some lower bound and upper bound.  However, repeated addition of 0.01 would result in accumulation of round-off errors, so a workaround is used.

pow(x, 2) could be simplified to x * x.
Naming could be better.  I suggest:

pre → inv_delta_x (to emphasize its relationship to x)
fp → table, and fp2 → extrema (to explain the contents of the files)

Since you are already using C99-style comments, you should also take advantage of C99-style variable declarations, which allow you to declare variables closer to the point of use to enhance readability.

I've defined a FOR_RANGE() macro to make the loops in main() more readable, but that may be a controversial improvement.  I've also initialized min and max to INFINITY and -INFINITY, respectively, as a personal preference.

I agree that using recursion will probably yield unsatisfactory results, though I am unable to advise you further.  One of the comments above links to a related math question.  You will probably get a better answer about numerical methods on Computational Science SE.

#include <math.h>
#include <stdio.h>

// Singularity at x=0.0 raises exception FE_DIVBYZERO and/or sets errno to EDOM
float func(float x)
{
    return exp(x / 2) / (x * x);
}

#define FOR_RANGE(type, var, lower_bound, upper_bound, inv_delta) \
        for (type iteration_dummy = (lower_bound) * (inv_delta), var; \
             (var = iteration_dummy / (inv_delta)) <= (upper_bound); \
             iteration_dummy++)

int main(void)
{
    // We want to increment x in steps of 0.01, but repeatedly adding 0.01
    // would cause round-off errors to accumulate.  Therefore, we will divide
    // successive floating-point integers by 100 instead.
    const float inv_delta_x = 100.0;

    FILE *table   = fopen("Q3data.dat", "w+"),
         *extrema = fopen("Q3results.dat", "w+");

    float min = INFINITY;
    FOR_RANGE(float, x, 0.0, 20.0, inv_delta_x)
    {
        float y = func(x);
        if (y < min) min = y;
        fprintf(table, "%f\t%f\n", x, y);
    }

    fprintf(table, "\n\n");

    float max = -INFINITY;
    FOR_RANGE(float, x, -5.0, 5.0, inv_delta_x)
    {
        float y = func(x);
        float err;
        float nd1 = dfridr(func, x, 0.1, &err);
        float nd2 = dfridr2(x, 0.1);
        if (y > max) max = y;
        fprintf(table, "%f\t%f\t%f\t%f\n", x, y, nd1, nd2);
    }

    fprintf(extrema, "The minimum value of f(x) is %f when x is between 0 and 20.\n", min);
    fprintf(extrema, "The maximum value of f(x) is %f when x is between -5 and 5.\n", max);
    fclose(table);
    fclose(extrema);
    return 0;
}


my implementation of conway's game of life in C++

If you're going to use C++, make full use of the language. Create a class to hold your universe, then all of your non-main functions can be members. You also won't have to pass around a reference to the universe array as it would be a member of the class.
One alternative to the toKill and toBirth vectors is to have two "universe" arrays. You'd use one as the source, and copy over and update the values into the second, then trade off which array you modify on the next pass thru. cellFate would return the new (updated) value for that cell, and killOrBirthCells would be eliminated.
getNeighborCount is only using i and j as offsets to the x and y values. You can redo the loops to directly update the x and y values, and also handle the edge clipping by proper tracking of the start and end values for the loops. It would also be easy to exclude the cell itself.
Combining all that we get a new getNeighborCount (that would be a member of a class):
int Universe::getNeighborCount(Pos cellPos) const {
    int count = 0;
    int sx = std::max(cellPos.x - 1, 0);
    int ex = std::min(cellPos.x + 1, SIZE - 1);
    int sy = std::max(cellPos.y - 1, 0);
    int ey - std::min(cellPos.y + 1, SIZE - 1);
    for (int y = sy; y <= ey; ++y) {
        for (int x = sx; x <= ex; ++x) {
            if (y != cellPos.y || x != cellPos.x) {
                if (universe[y][x] == 1)
                    count++;
            }
        }
    }
    return count;
}

You may be able to reduce flickering by moving the system("cls"); call to immediately before the call to printUniverse. This would reduce the amount of time that you have an empty screen.


With checked[0] you are getting a reference to the actual DOM element (instead of the jQuery object) but that is unnecessary in your case since jQuery provides a val() method, which returns the current value of the first element in the set of matched elements. So in your case, you could simply do:

var checkedVal = form.find(".radio-Class:checked").val();

A better way to get the selected value as pointed out here by @Peter J is to use the input[name=radioName]:checked selector. Selecting through name attributes ensures that you select the desired radio group since these are meant to be unique. For better performance, you can pass in the form id as the second argument inside the selector method, which is used as a context here (this is same as if you would use $("#form").find("input[name=radioName]:checked")), here is the refactored code:

$("#form").submit(function(event) {
  var $formEl = $(this);
  var $labelEl = $formEl.find('#label1');
  var radioVal = $('input[name=RegimenReferences]:checked', $formEl).val();

  event.preventDefault();
  $labelEl.text(radioVal);
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#form {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

<form id="form" class="form-horizontal" data-sortorder="1">

Update Values

  1

      <input type="radio" id="radio1" name="RegimenReferences" value="1" class="radio-Class" checked='true'>
      (a) aaaaaa

      <input type="radio" id="radio2" name="RegimenReferences" value="2" class="radio-Class">
      (b) bbbbbb

      <input type="radio" id="radio3" name="RegimenReferences" value="3" class="radio-Class">
      (c) cccccc

      <input type="radio" id="radio4" name="RegimenReferences" value="4" class="radio-Class">
      (c) cccccc

    <button type="submit" class="btn btn-primary modal-submit-btn">Save</button>
    <button type="button" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>

</form>

Edit 1:
Since you already got the form selected you can pass that as the context therefore you don't need the form id.


A standard dummy node trick (along with appropriate Node::Node constructors) greatly simplifies the code:

    SimpleVector::SimpleVector(const SimpleVector &obj)
    {
        Node dummy;

        for (Node * o = obj.head, *n = &dummy; o; o = o->next) {
            n->next = new Node(o->value);
            n = n->next;
        }

        this->head = dummy.next;
    }

To utilize STL, you need to implement iterators.


Produce all multiples of a set of primes up to a certain limit

Give variables better names, exponent is better than x.
List comprehensions make your code more understandable.
You can use dictionary.values() to get a list of the values.
You should make this a function. If you can change; limit, and primes.
You're not just getting multiples, you're also getting exponents too. So you may want a better function / variable name.

This can get you:

from collections import defaultdict
from itertools import combinations
from math import log

def prime_multiples(limit, primes):
    res = defaultdict(list)
    res[()] = [1]

    for n in range(1, len(primes) + 1):
        for combo in combinations(primes, n):
            base = combo[-1]
            res[combo] = [
                multiple * base**exponent
                for multiple in res[combo[:-1]]
                for exponent in range(1, int(log(limit / multiple, base)) + 1)
            ]

    multiples = [i for val in key.values() for i in val]
    multiples.sort()
    return multiples

print(prime_multiples(10**13, [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]))

It's 5AM, and I've not tested the following in anyway.
But you could probably change the code to use the modulo operator, %.
To check if the number is devisable.
And so if you write a generator function, you may be able to use:

def prime_multiples(limit, primes):
    yield 1
    for num in range(1, limit):
        if any(num % prime == 0 for prime in primes):
            yield num


Implementation of a simple stack with min method

It all depends how much time you had to do this, overall it looks ok. In a couple of places you are initializing in the body of the constructor rather than using the initializer list, that is if nothing somewhat inconsistent but you should be using the initializer list in all of these cases. Also the way you use it, the stackNode constructor might as well take the next pointer, this way you don't forget to set it. I might try and get you to figure that out via questions about the constructor.

There is no way to get to value of the top of the stack, pop doesn't return it, neither is there a top() function that would return the top value.

I'd probably also would like to see an error condition rather than the default constructed value being returned for minimum() and pop(). It's worse for minimum because you are returning a valid value e.g. int() for an empty stack, i.e. calling minimum() on an empty stack<int> will return 0. That is just plain wrong therefore a bug.

I'd probably ask you why you consider min a temporary, this is from the comment in pop() just to clarify language.

stackNode* push(T val, stackNode *head) should be private

Algorithm wise it looks like a reasonable solution, depending on how the inteview goes i might ask you follow up questions, e.g. could you come up with a solution that doesn't need two separate stacks, these days I'd also ask you how to make this datastructure thread safe. I might ask what requirements there are to type T and what might happen if they aren't fulfilled. Maybe again depending how the interview goes, how to extend the stack to allow classes that don't fulfill the requirements to still used for the stack.


The problems start with this code being fairly unreadable. A few simple rules can help:

Every comma is followed by a space: xi, yi instead of xi,yi.
Every binary operator like + is surrounded by a space on each side:

int(round((xi[i] - xEast) / res, 0) + 1)

instead of int(round((xi[i]-xEast)/res,0)+1).
If an expression becomes to complicated, assign intermediate values to variables which also assist in explaining the code to a reader:

start = l * i
end = l * (i + 1)
chunk_x = xi[start:end]
chunk_y = yi[start:end]
interp = rbfInterp(x, y, temp0m, chunk_x, chunk_y)
result = interpData(chunk_x, chunk_y, z, interp, xEast, ySouth, xWest, yNorth, res)
grid2 += list(result)[start:end]

instead of

interp = rbfInterp(x,y,temp0m,xi[(l*i):(l*(i+1))],yi[(l*i):(l*(i+1))])
grid2 = grid2 + list(interpData(xi[(l*i):(l*(i+1))],yi[(l*i):(l*(i+1))],z,interp,xEast,ySouth,xWest,yNorth,res))[(l*i):(l*(i+1))]

At least try to provide meaningful names for your variables. Expressions like tmp2[tmp1] are unacceptable.
Avoid overly clever things like append = t.append; …; append(…), as you gain nothing by this indirection. t.append(…) directly.
In a function call, never put a space between the function name and the parens.

plot(x, y, temp0m, grid2) instead of plot (x,y,temp0m,grid2)
append(None) instead of append (None)

Most of Python is using the convention that variable names should use snake_case not camelCase. While consistency is more important than following any specific style, I suggest you adopt this common style.
Some variable names like chunkSize are misleading – this is the number of chunks, not their size.

Once we have cleaned up the code, we can investigate where performance could be increased. This is done mostly by avoiding unnecessary recalculations, but also by finding more efficient expressions.

For example, Rbf(x, y, temp0m, function='linear') will always produce the same value as the parameters never change. Therefore, calculate it once outside of any loops. Actually, you can remove the whole rbfInterp function.

Inside interpData, you translate and rescale the data: (yi[i]-ySouth)/res. If you do this outside of an explicit loop, then numpy can do this more efficiently: translated_yi = (yi - ySouth)/res.

The whole meshgrid business is obfuscating which calculation you are actually performing:

# prepare an interpolation function for this data
interpolation_function = Rbf(x, y, temp0m, function='linear')

# the actual coordinates
yis = np.linspace(ySouth + 0.1, yNorth - 0.1, ny)
xis = np.linspace(xEast + 0.1, xWest - 0.1, nx)

# the grid positions in the data file
yis_normalized = ((yis - ySouth)/res).round(0).astype(np.int)
xis_normalized = ((xis - xEast)/res + 1).round(0).astype(np.int)

grid = np.zeros((ny, nx))
for i in range(ny):
    heights = linecache.getline('dem_final2.txt', yis_normalized[i]).split(' ')
    for j in range(nx):
        height = float(height[xis_normalized[j]])
        result = height * z + interpolation_function(xis[j], yis[i])
        grid[i][j] = result if data_item > -10 else np.nan

Some important points:

We fetch and parse each line once per line, instead of once per grid column.
We factor out repeated calculations outside of the loops
We avoid any confusing reshaping by writing the results directly into the correct data structure.
We try to avoid explicit loops by using numpy transformations

The purpose of the code is now much more obvious.

However, the usage of linecache is quite suspicious. We read the lines in sequential order, so caching will be of no use → read the file manually. You should also consider reading it into a numpy array, as the file in this form should only be using a few MB of memory:

heights = np.loadtxt('dem_final2.txt')
...
result = heights[yis_normalized[i]][xis_normalized[j]] * z + ...


I really think that you should merge all of these if statements, make them an if/elseif/else statement.  just move all the variable declarations to the top.

then it turns into this

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Authorize(Administrator a)
{
    var admin = _db.Administrators.Where(x => x.Username == a.Username).SingleOrDefault();
    ICryptoService cryptoService = new PBKDF2();
    string hash = cryptoService.Compute(a.Password, admin.PasswordSalt);
    if (!this.CanAdminLogin) // Check if there are no failed login attempts in last 5 minutes
    {
        TempData["loginTooManyAttempts"] = true;
        return RedirectToAction("index", "home");
    }
    else if (!TryValidateModel(a)) // If model is not validated return login view to show error messages (javascript disabled)
    {
        return View("Authorize", a);
    }
    else if (admin == null || admin.Username != a.Username) // Check if username exists, if not then log and show that login failed
    {
        this.LogAuthorization(a, false);
        TempData["loginFailed"] = true;
        return RedirectToAction("index", "home");
    }
    else if (hash == admin.Password) // Username exists, check if passwords match
    {
        this.LogAuthorization(a, true);
        Session["adminId"] = admin.ID;
    }
    else
    {
        this.LogAuthorization(a, false);
        TempData["loginFailed"] = true;
    }

    // Login successfull
    return RedirectToAction("index", "home");
}

I also moved the comments to the end of the line that they attach to.  Keep in mind that some of these comments are not needed at all.

The Comments that are needed here

// Check if there are no failed login attempts in last 5 minutes

This is only needed because otherwise I wouldn't have known why the Admin couldn't log in or that there was an instance that would change this boolean.

// If model is not validated return login view to show error messages (javascript disabled)

I can tell from the code what is going on, but I am not sure what (javascript disabled) has to do with this code?


Swapping every letter with every other letter in a string

to swap every letter with every other letter in a string

In other words you need all permutations of a string. Ok not all: no need in null set.

  I would just like to make it efficient as possible.

Just wanted to show you another solution. A crazy one with a recursion:
https://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string

public static void permutation(String str) {
    permutation("", str);
}

private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}

Quick solution to get it in one line with commas:

public static String permutation(String str) {
        String res = permutation("", str);
        return res.substring(0, res.length()-2);
    }

private static String permutation(String prefix, String str) {
    String res = "";
    int n = str.length();
    if (n == 0) res = res + prefix + ", ";
    else {
         for (int i = 0; i < n; i++)
             res = res + permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
    return res;
 }

Output:
rya, ray, yra, yar, ary, ayr

Less code, but definitely not the most efficient: calling charAt and substring a lot of time - not a good way.

In that link there are alot of other examples how to do it.


Before we can do anything here really, we need to clean this up so we can understand exactly what's going on.

To start with, let's remove some duplication. This code is copy/pasted all over the place, but no matter what happens, it executes.

If Not (rs1.EOF And rs1.BOF) Then
    strPD = CDbl(rs1![PD])
Else
    strPD = "0.0229"
End If

strSQL = "update output set [PD] = '" + Format(strPD, "#.0000000000000") + "'  WHERE [OUTPUT].[CIF]='" + CStr(strCIF) + "' AND [OUTPUT].RUN_NUMBER='" + runNumber + "'"
Debug.Print strSQL
CurrentDb.Execute (strSQL)

    If (strOrigGroup = "CB" Or strOrigGroup = "FID" Or strOrigGroup = "PB") Then

            strSQL1 = " SELECT DISTINCT  [INPUT].RUN_NUMBER, [INPUT].CIF, INPUT.CIF_2,[PD].[MID_PD] FROM [PD] INNER JOIN [INPUT] " + _
                      "ON [PD].CIF=[INPUT].CIF_2  WHERE [PD].[CIF]='" + strCIF2 + "' and [INPUT].RUN_NUMBER='" + runNumber + "'"
            Debug.Print strSQL1
            Set rs1 = CurrentDb.OpenRecordset(strSQL1)

    ElseIf (strBaselAsset = "BK" Or strBaselAsset = "BO" Or strBaselAsset = "SK") Then

         strSQL1 = "SELECT DISTINCT [INPUT].RUN_NUMBER,  [INPUT].CIF, [PD_MASTER_CPTY].[PD] FROM PD_MASTER_CPTY INNER JOIN INPUT ON [PD_MASTER_CPTY].COUNTERPARTY=INPUT.[CPTY-BA] WHERE [PD_MASTER_CPTY].[COUNTERPARTY]='" + strBaselAsset + "'AND [INPUT].CIF_2='" + CStr(strCIF2) + "' and [INPUT].RUN_NUMBER='" + runNumber + "'"
         Debug.Print strSQL1
         Set rs1 = CurrentDb.OpenRecordset(strSQL1)
    Else
        strSQL1 = "SELECT [INPUT].RUN_NUMBER, [INPUT].CIF,[PD_MASTER_BG].[PD] FROM [PD_MASTER_BG] INNER JOIN INPUT ON [PD_MASTER_BG].[BUSINESS_GROUP]=INPUT.[ORIGINAL GROUP] WHERE [PD_MASTER_BG].[BUSINESS_GROUP]='" + strOrigGroup + "'AND [INPUT].CIF_2='" + CStr(strCIF2) + "' and [INPUT].RUN_NUMBER='" + runNumber + "'"
        Debug.Print strSQL1
        Set rs1 = CurrentDb.OpenRecordset(strSQL1)
    End If

    If Not (rs1.EOF And rs1.BOF) Then
        strPD = CDbl(rs1![PD])
    Else
        strPD = "0.0229"
    End If

    strSQL = "update output set [PD] = '" + Format(strPD, "#.0000000000000") + "'  WHERE [OUTPUT].[CIF]='" + CStr(strCIF) + "' AND [OUTPUT].RUN_NUMBER='" + runNumber + "'"
    Debug.Print strSQL
    CurrentDb.Execute (strSQL)

    rs.MoveNext
Loop

Next, give your SQL statement variables some meaningful names. I shouldn't have to keep reminding myself that strSQL1 is the select statement and strSQL is the update. Try selectSQL and updateSQL respectively.

Next, I would separate the messy business of creating the string to be executed from the business of actually executing.

Private Function BuildSelectStatement(byval cif as string, byval runNumber as integer, Optional byval baselAsset as String) As String
    ...
End Function

....

selectSQL = BuildSelectStatement(strCIF2, runNumber)

Which brings me to recommending that you use ADODB for this. The only time it's really important to stick with DAO is when you intend on binding a form to the resulting Recordset. Instead of concatenating all of these parameters into strings, you could instead be passing parameter into parameterized queries. It looks and reads much better than this.


Calculates the Average Score of Given Number of Scores in C

Reduce the number of loops
The most time-consuming part of your program is to loop through the array. Notice that you have done this twice, why can't you keep a track of the total sum while taking the input?
#include <stdio.h>

float average(int sum,int number);

int main(void)
{
    int number_of_integers,number,sum = 0;
    printf("Enter the number of integers: ");
    scanf("%d",&number_of_integers);
    for(int i = 0;i < number_of_integers;i++)
    {
        printf("Enter: ");
        scanf("%d",&number);
        sum+=number;
    }
    printf("Average = %d",average(sum,number_of_integers));
}

float average(int sum, int number)
{
    return sum/(float)number;
}

This reduces the number of loops from 2 into 1. And completely removes the need of having an array of integers. Making your program both memory efficient and fast.


The data structure you want is called a trie.  It's often used with letters in the nodes, for doing word search (finding anagrams and so on); in your case the keys would be words and the values would be sub-tries and arrays of line numbers or other metadata.

Given this input:

cat dog pig
dog pig cow

You'd make a structure like:

{
    cat: {
      dog: {
        pig: { "#": [ 1 ] },
        "#": [ 1 ]
      },
      "#": [ 1 ]
    },
    dog: {
      pig: {
        cow: { "#": [ 2 ] },
        "#": [ 1, 2 ]
      },
      "#": [ 1, 2 ]
    },
    pig: {
      cow: { "#": [ 2 ] },
      "#": [ 1, 2 ]
    },
    cow: { "#": [ 2 ] },
}


Writing nested for loops to produce certain output

You're not breaking up the patterns in the most logical way.  Each line just consists of repeating blocks of three characters.

public class SquigglePlus {
    private static final String[] PATTERNS = { "~~~", "~+~", "+~+", "~~~" };

    public static void main(String[] args) {
        for (int line = 0; line < PATTERNS.length; line++) {
            for (int col = 0; col < 48; col += PATTERNS[line].length()) {
                System.out.print(PATTERNS[line]);
            }
            System.out.println();
        }
    }
}

Alternatively, the inner loop could just count to 16: for (int i = 0; i < 16; i++) { … }.  Note that in Java, that is the most idiomatic way to count: start with 0, and use < for the termination check.  The other way (for (int i = 1; i <= 16; i++) { … }) would not be wrong, but usually you would write it that way only if you had a special reason.

Better yet, use a modern enhanced for-loop instead of the old-style counting loop.

public class SquigglePlus {
    private static final String[] PATTERNS = { "~~~", "~+~", "+~+", "~~~" };

    public static void main(String[] args) {
        for (String pattern : PATTERNS) {
            for (int col = 0; col < 48; col += pattern.length()) {
                System.out.print(pattern);
            }
            System.out.println();
        }
    }
}


Unix shell function for adding directories to PATH

grep is most likely an overkill. After setting IFS=":", the $PATH is conveniently split into words. Then the presence of the directory can be determined in a simple loop

    IFS=":"
    for pathdir in $PATH; do
        if [ $pathdir == $1]; then return; fi
    done

    # Now restore IFS and modify path as needed.


Filtering script for products by category

I don't see how this is scalable if you have to hard code product id's into your jQuery code and duplicate handlers for every category you may want to add.

I also see no need to have separate logic for "first time" execution vs. every other time.

I would consider putting a data- attribute on each checkbox that can indicate the target category the checkbox filter is to work against. And then put a data- attribute on each product to indicate what category it belongs to.

So let's assume your products are like this:

...

...

And your category checkboxes are like:

<input class="category_filter" data-category-target="1" type="checkbox" value="first-checkbox" />
<input class="category_filter" data-category-target="2" type="checkbox" value="second-checkbox" />

Then your jQuery might be simplified down to something like:

// cache references to DOM elements to eliminate need to requery
var $categoryFilters = $('.category_filter');
var $allProducts = $('.product');
// build out selectors for each category
var productsByCategory = {};
$categoryFilters.each(function()) {
     var category = $(this).data('category-target');
     productsByCategory[category] = $allProducts.filter('[data-category=' + category + ']');
});

// now attach change handler to filters
$categoryFilters.on('change', function() {
    $allProducts.hide();
    $categoryFilters.each(function() {
        var target = $(this).data('category-target');
        if($(this).is(':checked')) {
            productsByCategory[target].show();
        }
    }
});

Why are you loading two versions of jQuery?  If this is absolutely unavoidable,  you should be aliasing these versions appropriately (i.e. to something other than $) so that you can write code against whichever version is pertinent to that section of code.

Anytime you find yourself duplicating code for cases like you have with #example-category-*, this should be an immediate red flag to you that have established a coding antipattern.  For this specific example, what you really have is class level behavior (all of the category checkboxes exhibit similar behavior in this case).  That typically mean you should be writing code against the class of elements, not against individual unique id's.


Scraping a webpage copying with the logic of scrapy

Even though you are trying to mimic what Scrapy spider might look like, there is a very major high-level difference between how your code is executed and how a Scrapy spider is.

Scrapy is entirely asynchronous since it is based on a twisted network library which makes the code operate in a non-blocking nature, to quote the documentation:

  Requests are scheduled and processed asynchronously. This means that
  Scrapy doesn’t need to wait for a request to be finished and
  processed, it can send another request or do other things in the
  meantime. This also means that other requests can keep going even if
  some request fails or an error happens while handling it.

But, in your case, you do go through the whole process in a blocking mode, processing requests one by one:

Extract tag links from the main page
Make a request to the next tag in the list and wait for the response
Extract quotes and print them
Extract the link to the next page and go to step number 2^

Every time requests make a request, you wait. Scrapy would do things while waiting, that's the main high-level difference.

And, by the way, if you would not assign priority values for your Scrapy requests (by default all requests have the same priority), there is no enforced order in which requests are gonna be processed.


Macro enabling Python style 'with' in C++

[ Foreword: Note that I'm not going to argue whether or not it is a good idea to invent a new macro-based syntax for this.  I'm only reviewing your code. — end foreword ]

I think you have been pretty careful and cannot spot any serious issues with your implementation; nice job.

The only thing that I think could be improved is the error reporting.  Your static_assertion fires much too late in the instantiation process such that the error message will end up buried under loads of template error messages.  You can re-structure the instantiation machinery to improve this.

First, provide two overloads of boost::with_detail::make_true:

template <class T>
std::true_type make_true(T&&, std::false_type) {
    static_assert(std::is_move_constructible<T>::value,
                  "BOOST_WITH requires the scoped object's type to be move"
                  " constructible");
    return std::true_type{};  // never executed
}

template <class T>
always_true<T> make_true(T&& what, std::true_type) {
    static_assert(std::is_move_constructible<T>::value, "this is a bug");
    return always_true<T>{std::forward<T>(what)};
}

The static_assertion in the second overload is of course only paranoia and could be omitted.

Second, select the appropriate overload via tag dispatch:

#define BOOST_WITH(RESOURCE)                                        \
  if (auto BOOST_WITH_always_true = boost::with_detail::make_true(  \
      RESOURCE,                                                     \
      std::is_move_constructible<decltype(RESOURCE)>{}))

With this change, if I try to abuse your macro with a wrong type, GCC gives me this pretty straight-forward error message:

In file included from main.cpp:1:0:
boost/with.hpp: In instantiation of ‘std::true_type boost::with_detail::make_true(T&&, std::false_type) [with T = std::mutex; std::true_type = std::integral_constant<bool, true>; std::false_type = std::integral_constant<bool, false>]’:
main.cpp:22:5:   required from here
boost/with.hpp:42:7: error: static assertion failed: BOOST_WITH requires the scoped object's type to be move constructible
       static_assert(std::is_move_constructible<T>::value,

Compare this with what we would have got before.

Note that we cannot simply put static_assert(false, …); inside the make_true body because it would fire unconditionally on every compilation.  It is necessary to make the asserted condition dependent on the template argument.  Of course, any other template instantiated with T that always yields false would do equally well but using std::is_move_constructible (again) seems easiest.


Finding median of sub arrays taking too much time

Not related to performance, but never ever do this:

#include <bits/stdc++.h>

using namespace std;

For reference see these Q&A at Stack Overflow:

Why should I not #include <bits/stdc++.h>?
Why is “using namespace std;” considered bad practice?


First off, what you currently have is perfectly fine. The only thing I would suggest is to use pathlib.Path instead of manually using format and consistently follow the PEP8 naming scheme by using lower_case and having spaces after commas in argument lists:
from pathlib import Path

file_name = Path(f).with_suffix(".txt")

I see two ways you could take this code. One direction is making it more memory efficient by using normal Python to parse the file. This would allow you to make the code fully streaming and process all files in one go:
import csv

def filter_column(files, column, value):
    out_file_name = ...
    with open(out_file_name, "w") as out_file:
        writer = csv.writer(out_file, sep=";")
        for file_name in files:
            with open(file_name) as in_file:
                reader = csv.reader(in_file, sep=";")
                col = next(reader).index(column)
                writer.writerows(row for row in reader if row[col] != value)

This has almost no memory consumption, due to the writerows, which probably consumes the generator expression after it. If you want it fully independent of your memory (as long as a row fits into memory):
                for row in reader:
                    if row[col] != value:
                        csv_writer.writerow(row)

The other possibility is to go parallel and distributed and use something like dask:
import dask.dataframe as dd

files = "file1.csv", "file2.csv"
df = dd.read_csv(files, sep=";")
df_out = df[df.LIB_SEGM_SR_ET != "PARTICULIERS"]
file_name = ...
df_out.compute().to_csv(file_name, index=False, sep=";")

This gives you the full ease of using pandas and splits the task into batches that fit into memory behind the scenes.


Conversion from RGB to CIELAB with a complex formula

The main thing that would speed it up is to not constantly calculate constant values. For example, you can replace:

pow ((6.0 / 29.0), 3.0)

with

0.00885645167904

Preferably you'll give it a name like:

let threshold = 0.00885645167904

Likewise for the other call to pow(). pow() is a very expensive function to compute, so removing it can be a big win.


I don't fully understand the purpose behind what you're doing so forgive me if I offer something that won't meet your needs.

It looks to me like what you want to do is use PHP to create a new image. Instead of echoing out divs, you can accomplish the same result by drawing filled rectangles into a new image created dynamically by PHP. Check out the PHP manual entry for imagefilledrectangle.
http://php.net/manual/en/function.imagefilledrectangle.php

From there, depending on how you're serving the image, you can either output it as base64 in an html image tag, or you can simply dump it to the client with an image header. For the dumping option if you're not familiar, the image src would point to your PHP file which would have headers telling the browser it was getting content of type image/png.

The good part of doing it this way is that you're almost there already. You just need a new image to write to, and then code to output it. As an alternative though you might consider doing this completely in JavaScript. You can load the image after the page loads (for best user experience), and then draw the results onto an HTML canvas element. If you don't like the canvas, you could still use this method to reproduce your original div system.


Deficiencies

What's this piecemeal approach to functional/imperative programming? It makes code difficult to understand. In a particular part of a program, try to stick to a particular paradigm (I can't believe I had to say that. Multiparadigm languages have come a long way!).

You seem to not have noticed the glory of import. The glorious import scala.annotation.tailrec at the start of SinglyLinkedList would make all the tail-recursion annotations in your methods to simply @tailrec.

Node[T] should ideally be a case class. That would give you proper, compiler-implemented equals, toString and hashCode methods, alongside having easy pattern matching support, and not requiring new to instantiate them. By the way, did you know that Some is a case class?

You seem to be using Option as a replacement for null. IMHO, it complicates your code. Just use null if you have to. You're implementing the singly-linked list in classic reference/pointer based way after all. Don't get me wrong here, using Option is definitely better than using null, but I think it overcomplicates your code.

Do take a look at cons lists. I guess that's what you actually want.

Finally, a reference based list is not idiomatic Scala. A cons list (as above) is. Try to use that, it's not too far from what you're currently doing (I do hope that you want to do it the functional programming way, as you have not stated otherwise). As this is already not idiomatic Scala, you could go the full imperative route with while loops and null, as Scala allows you to do so. Or you could go the functional route with full immutability and cons lists. The choice is yours, but in this case, I and most other Scala programmers would recommend you choose the latter option. But whatever you do, keep this Frankenstein's monster imperative/functional hybrid from most people.

Suggestions

For remove(Int):Int, an algorithm is to do it the normal, C (pointer-based way). Traverse the list maintaining references to 2 elements, the current element and it's previous element. At the element to be removed, set the next field of the previous reference to refer to the element following the current element. This would work far better with while loops than flatMap and forEach. Again, imperative and functional don't really mix well in the same part of the program.

Take a look here for a reasonable functional singly linked list in Scala.


I'm not sure what you're intending to do with this class so I can only offer some general tips.

Make private variables private:

def __init__(self, url):
    self._url = url

Use properties instead of get_ methods. For example:

@property
def request(self):
    return self._requests.get(self._url)

# to make it writeable:
@request.setter
def request(self, value):
    self._requests.set(value)

If you're using Python 3, have a look at abc.ABCMeta for better solution for abstract base classes with abstract methods.


Answering whether or not this implementation is correct would require to know what the specification of the problem is. Now assuming the spec is:

  Create a queue to which multiple threads can add items and multiple threads can remove item. The queue will hold no more than 1000 string references and blocks writers when the queue is full and readers when the queue is empty.

then I'd say yes your implementation will achieve that.

Some remarks:

As mentioned by @svick you should seriously consider using BlockingCollection which was added in .NET 4.0.
You can increase the practical usefulness immediately by doing two simple things

Make your class generic. This way you can create a blocking queue for any type not just string.
Let the user pass in the capacity.

Some future speculation in case you are stuck with .NET 3.5 or earlier and want to stick with your implementation: If you are ever tempted to implement IEnumerable<T> (to show the content in a UI for example) on your class then remember that the following implementation is broken (I have seen this more often than I'd like):

public IEnumerator<T> GetEnumerator()
{
    lock (_door)
    {
        return _myQueue.GetEnumerator();
    }
}

The correct way would be to make a local copy of the queue (inside the lock) and return the enumerator to that. The other option is to iterate over the queue inside the lock and yield the items which effectively locks the queue for the entire duration of the enumeration. However this is probably a bad idea since a caller which is not aware of this can easily lock out all access to the queue for a long period of time.


Pull data from database to generate XML files

The program asks to input the time first,
before trying to connect to the database.
If the database connection fails,
the user might be frustrated for having entered something only to watch the program crash.
It would be better to move the input part right before it's really needed.

There are some unused elements:

use File::Slurp; appears twice, delete the second
@matrix is never used

The comment at the end of this line is pointless:

my ($time, $report) = @row; #time, report


The code you've provided is fairly thin and so there's not to much to pick at here, however, I think your checks on roles and cbs can be simplified using Array.isArray(), because the for of iterator cannot iterate an empty array.

if (roles && roles.length) {
  for (let role of roles) {
    if (userRoles.indexOf(role) !== -1) return next();
  }
}

can be transformed to:

if (Array.isArray(roles)) {
  for (let role of roles) {
    if (userRoles.indexOf(role) !== -1) return next();
  }
}

Although I think these checks would be better moved up and for you to return a 500 Server Error if roles or cbs aren't arrays.

In the same block of code you have indexOf(role) !== -1, which was simplified to .includes(role) in ES6.

The only other thing that comes to mind is the userRoles.split(',') call, because, if userRoles isn't a string, it'll raise an exception. However, that would depend on how malleable your database / validation is.

Additionally, your second suggested prototype has way more confusing usage than your implementation, I would stick with what you've created.


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

Use const where practical

The print_time24() and print_time12() functions only print and do not modify the underlying Time object, so they should both be declared const:

void print_time24() const;
void print_time12() const;

Make printing prettier

The current print_time24() routine does not emit nice looking time.  If the time is 12:06:07, the program emits 12:6:7 which is not quite right.  Instead, you have to format the data so that minutes and seconds are both two digits.  I show how in the next comment.

Create a stream inserter

Right now the code is only capable of printing to std::cout and not a std::stringstream or std::ofstream.  This can be fixed by one of two ways.  Either you can add a std::ostream& parameter to each of the print routines or you can create a friend inserter like this:

friend std::ostream& operator<<(std::ostream& out, const Time& t) {
    auto oldfill = out.fill('0');
    return out << t.hr
        << ':' << std::setw(2) << t.min
        << ':' << std::setw(2) << t.sec << std::setfill(oldfill);
}

You will also have to #include <iomanip>.  Now it can be used like so:

cout << t << '\n';

Think of the user

While the add_min() routine does indeed add exactly 1 minute, I would instead have expected that one would be able to add an arbitrary number of minutes instead, as with add_min(int minutes).

Also, it seems likely that a user would have a preference for either AM/PM or 24-hour time.  I'd suggest making that preference either a boolean data member of the class or perhaps a static data member for all instances of the class.

Consider signed vs. unsigned

Would a time of -3:-80:-155 be something you would recognize as a time?  Probably not, but unfortunately your Time object has no problem with that. Both the constructor arguments and the private data members should be unsigned rather than int.  If you want to save some space, you could even declare the private data members as unsigned char.

Use braces

Lines like this:

if (am_or_pm == "AM" && hr == 12)
    hr = 0;

while technically accurate are a potential error waiting to happen.  The problem is that if someone adds a line, perhaps for troubleshooting or diagnostics, the if statement will break unless braces are added.  You can both make your code more clear and prevent this kind of future error by using braces.

Handle out-of-range constructor arguments

There are two choices for how to handle invalid constructor arguments.  Either you can ignore them and silently substitute a default or throw an error.  I'd recommend the latter approach.  At the bottom of your constructor, add these three lines:

if (hr > 24 || min > 59 || sec > 59) {
    throw(std::domain_error("Time value out of range"));
}

You will also have to #include <stdexcept>.

Use helper functions to make code simpler

The code to print the time could be much simpler if you use helper functions.  I'd suggest these member functions:

    bool is_pm() const {
        return hr >= 12;
    }
private:
    unsigned get_hour(bool am_pm) const {
        if (!am_pm)
            return hr;
        if (is_pm())
            return hr-12;
        if (hr == 0)
            return 12;
        return hr;
    }
    const char *get_suffix(bool am_pm) const {
        if (!am_pm)
            return "";
        if (is_pm())
            return " PM";
        return " AM";
    }

Now the two separate print routines can be refactored as one member function taking a bool to tell whether to print 24-hour or AM/PM time:

std::ostream& print(std::ostream &out, bool am_pm) const
{
    auto oldfill = out.fill('0');
    return out << get_hour(am_pm)
        << ':' << std::setw(2) << min
        << ':' << std::setw(2) << sec
        << get_suffix(am_pm)
        << std::setfill(oldfill);
}

This, in turn can be used by the friend inserter I mentioned above:

friend std::ostream& operator<<(std::ostream& out, const Time& t) {
    return t.print(out, false);
}

Simplify the add_min() code

The code does more mathematics than it needs to.  Now that the constructor throws an error if it's malformed, we know that the stored values are always valid.  This means that the add_min() code can be simplified:

void Time::add_min()
{
    if (++min > 60) {
        hr = (hr + 1) % 24;
        min = 0;
    }
}

Eliminate return 0 at the end of main

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.


Right, so I've got a few suggestions.

First, instead of making ourselves worry about non-bracket characters, let's trim them out:

string = string.replaceAll("[^\\[\\]\\{\\}\\(\\)]", "");

You'll have to remove the final modifier, which I can't see a reason for anyway. Also, you never actually caused an error if character wasn't a bracket, so the code still ends up working the same. It's just less to worry about.

Note: Technically, since this code ignores all non-bracket characters, this statement isn't necessary. If you comment it out, the rest of the code should still work fine. Still, I like explicitly saying, in code, that my thing ignores your petty brackets and mustaches.

Second, let's define a private static final Map<Character, Character> MATCHING_CHARS1 to store the pairs, instead of hardcoding them. That way, instead of checking if something matches one of three hard-coded brackets, we can do this:

if (MATCHING_CHARS.containsKey(character)) {

And instead of peek()ing once per bracket, we do it a flat rate of once:

else if (!bracketStack.empty() &&
    MATCHING_CHARS.get(bracketStack.peek()) == character) {

Note that since get returns null when the key isn't there, it automagically doesn't give a crap if the character isn't in MATCHING_CHARS! (and also doesn't match)

And finally, we replace your last if with:

else if (MATCHING_CHARS.containsValue(character)) {

Whew! Much simpler. Now, unless you plan to synchronize that regex we used at the beginning and the map for any brackets you add in the future, I suggest we do this:

private static final String REMOVE_REGEX = "[^\\" + String.join("\\",
    MATCHING_CHARS.values().appendAll(MATCHING_CHARS.keys()) // every bracket
) + "]"; //for brackets 'a', 'b', 'c' should be "[^\\a\\b\\c]"

Then we use that in the place of the regex from before.

Actually, I don't suggest we do that awful mess of a line, I suggest we use a language where it's easier to get the behavior I'm looking for and doesn't require ugly hacks, but whatever. Ya make do with what you've got.

Now, one last tip: Don't name things string. Name it checking or toCheck or something that describes its purpose. Java's a statically-typed language; we can tell that it's a String without you naming it that.


Return Early

If you extract the PHP code to a function, you can return early, and thus save a level of nesting:

<ul id="nav">
<?php printNavigation(); ?>
</ul>

<?php
function printNavigation() {
    if(!($grabNav = $db->prepare("SELECT caption,url,visibility,id,class,parent_id FROM navigation ORDER BY parent_id ASC, order_id ASC"))) {
        return;
    }
    [...]
    ?>
}

Remove Duplication and further simplifications

Currently, your visibility check and your one long echo line are duplicates. You can extract these to functions:

function isVisible($visibilityLevel, $cUser) {
    switch($visibilityLevel, $cUser)
    {
        case 0: return false;
        case 1: return true;
        case 2: return LOGGED_IN && isset($cUser);
        case 3: return !LOGGED_IN || !isset($cUser);
        default: throw new Exception('invalid visibility level.');
    }
}

And then use it as

    foreach($grabNav as $nav)
    {
        if(!isVisible($nav['visibility'], $cUser) || $nav['parent_id'] != -1) { continue; }
        [...]

Note also that I removed the useless default from the beginning of the switch, added it again at the end, and threw an exception for invalid values.

I also simplified cases 2 and 3 (if (cond) true else false can be phrased as cond), and I combined the two continue conditions.


Simple React component to view cached data and test result from API

You can just remove the TODO until it's needed. The code will be easier to follow and if someone needs to localize later, they can figure it out themselves. It's clutter.
DataRevealActions would probably be nice to pass in as properties, so the component is configurable. You could pass it in as now, or just have two different properties, getCachedData and transformData.

Otherwise, looks great!


Finding tuples of numbers subject to constraints

f != p != s does not prevent f and s from being equal

You can improve your algorithmic approach, using your constraints:

def iter_permutations():
    total = 12
    for f in range(1, 8):        # Fire must be between 1 and 7
        for p in range(2, 8, 2): # Police must be even
            s = total - p - f    # The sum must be 12
            if 0 < s < 8 and f != p != s != f: # They must be all different
                 yield f, p, s   # Use an iterator, because it's elegant!

You can simply use it with : for f, p, s in iter_permutations():

I think using an iterator is nicer than a list (you can easily get a list with list(iter_permutations()) if needed)


In order to properly give precedence to higher DPI images, you need to do three separate finds like your code already does. However, this part can be cleaned up, as well as getting rid of the unnecessary icon.try do ... end call.

begin
  icon = icons.find { |name, _| name.downcase.include? 'xxxhdpi' }
      || icons.find { |name, _| name.downcase.include? 'xxhdpi' }
      || icons.find { |name, _| name.downcase.include? 'xhdpi' }

  return unless icon.defined?

  File.open(tmp_icon.path.to_s, 'wb') { |f| f.write icon[:data] }
  s3_icon = bucket.objects[icon_path].write(Pathname.new(tmp_icon.path),
                                            content_type: 'image/png')
  icon_url = s3_icon.public_url(secure: true)
ensure
  tmp_icon.close
  tmp_icon.unlink
end


I believe  the GetDefaultView method is the bottle neck. If you refer to the source code you'll see that there are serverals loops involved in getting the view:
You start here:
public static ICollectionView GetDefaultView(object source)
{
    return GetOriginalView(GetDefaultCollectionView(source, true));
}

it calls:
static internal CollectionView GetDefaultCollectionView(object source, bool createView, Func<object, object> GetSourceItem=null)
{
    if (!IsValidSourceForView(source))
        return null;

    DataBindEngine engine = DataBindEngine.CurrentDataBindEngine;
    ViewRecord viewRecord = engine.GetViewRecord(source, DefaultSource, null, createView, GetSourceItem);

    return (viewRecord != null) ? (CollectionView)viewRecord.View : null;
}

it then calls the GetViewRecord which seems to be really heavy:
internal ViewRecord GetViewRecord(object collection, CollectionViewSource cvs, Type collectionViewType, bool createView, Func<object, object> GetSourceItem)
{
    // Order of precendence in acquiring the View:
    // 0) If  collection is already a CollectionView, return it.
    // 1) If the CollectionView for this collection has been cached, then
    //    return the cached instance.
    // 2) If a CollectionView derived type has been passed in collectionViewType
    //    create an instance of that Type
    // 3) If the collection is an ICollectionViewFactory use ICVF.CreateView()
    //    from the collection
    // 4) If the collection is an IListSource call GetList() and perform 5),
    //    etc. on the returned list
    // 5) If the collection is an IBindingList return a new BindingListCollectionView
    // 6) If the collection is an IList return a new ListCollectionView
    // 7) If the collection is an IEnumerable, return a new CollectionView
    //    (it uses the ListEnumerable wrapper)
    // 8) return null
    // An IListSource must share the view with its underlying list.

    // if the view already exists, just return it
    // Also, return null if it doesn't exist and we're called in "lazy" mode
    ViewRecord viewRecord = GetExistingView(collection, cvs, collectionViewType, GetSourceItem);
    if (viewRecord != null || !createView)
    {
        return viewRecord;
    }

    // If the collection is an IListSource, it uses the same view as its
    // underlying list.
    IListSource ils = collection as IListSource;
    IList ilsList = null;
    if (ils != null)
    {
        ilsList = ils.GetList();
        viewRecord = GetExistingView(ilsList, cvs, collectionViewType, GetSourceItem);

        if (viewRecord != null)
        {
            return CacheView(collection, cvs, (CollectionView)viewRecord.View, viewRecord);
        }
    }

    // Create a new view
    ICollectionView icv = collection as ICollectionView;

    if (icv != null)
    {
        icv = new CollectionViewProxy(icv);
    }
    else if (collectionViewType == null)
    {
        // Caller didn't specify a type for the view.
        ICollectionViewFactory icvf = collection as ICollectionViewFactory;
        if (icvf != null)
        {
            // collection is a view factory - call its factory method
            icv = icvf.CreateView();
        }
        else
        {
            // collection is not a factory - create an appropriate view
            IList il = (ilsList != null) ? ilsList : collection as IList;
            if (il != null)
            {
                // create a view on an IList or IBindingList
                IBindingList ibl = il as IBindingList;
                if (ibl != null)
                    icv = new BindingListCollectionView(ibl);
                else
                    icv = new ListCollectionView(il);
            }
            else
            {
                // collection is not IList, wrap it
                IEnumerable ie = collection as IEnumerable;
                if (ie != null)
                {
                    icv = new EnumerableCollectionView(ie);
                }
            }
        }
    }
    else
    {
        // caller specified a type for the view.  Try to honor it.
        if (!typeof(ICollectionView).IsAssignableFrom(collectionViewType))
            throw new ArgumentException(SR.Get(SRID.CollectionView_WrongType, collectionViewType.Name));

        // if collection is IListSource, get its list first (bug 1023903)
        object arg = (ilsList != null) ? ilsList : collection;

        try
        {
            icv = Activator.CreateInstance(collectionViewType,
                            System.Reflection.BindingFlags.CreateInstance, null,
                            new object[1]{arg}, null) as ICollectionView;
        }
        catch (MissingMethodException e)
        {
            throw new ArgumentException(SR.Get(SRID.CollectionView_ViewTypeInsufficient,
                            collectionViewType.Name, collection.GetType()), e);
        }
    }

    // if we got a view, add it to the tables
    if (icv != null)
    {
        // if the view doesn't derive from CollectionView, create a proxy that does
        CollectionView cv = icv as CollectionView;
        if (cv == null)
            cv = new CollectionViewProxy(icv);

        if (ilsList != null)    // IListSource's list shares the same view
            viewRecord = CacheView(ilsList, cvs, cv, null);

        viewRecord = CacheView(collection, cvs, cv, viewRecord);

        // raise the event for a new view
        BindingOperations.OnCollectionViewRegistering(cv);
    }

    return viewRecord;
}

who knows what eles it does :-)
then finally there is another loop involved here:
// return the original (un-proxied) view for the given view
static ICollectionView GetOriginalView(ICollectionView view)
{
    for (   CollectionViewProxy proxy = view as CollectionViewProxy;
            proxy != null;
            proxy = view as CollectionViewProxy)
    {
        view = proxy.ProxiedView;
    }

    return view;
}

Refactoring
I suggest you refactor your SearchGrid in a way that you retrieve the view somewhere else and here just update the filter:
private ICollectionView _view;

private void InitializeSearchView()
{
    view = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
}

private void SearchGrid(object sender, TextChangedEventArgs e)
{
    if (string.IsNullOrEmpty(searchBox.Text))
    {
        FillDataGrid();
        return;
    }

    var searchText = CharactersOnly(searchBox.Text);
    _view.Filter = (obj =>
    {
        CompanyModel compDetails = obj as CompanyModel;
        if (compDetails == null)
        {
            return true;
        }

        if (compNameRad.IsChecked == true)
        {
            return CompanyContains(compDetails.CompanyName, searchText);
        }
        if (compTownRad.IsChecked == true)
        {
            return CompanyContains(compDetails.CompanyTown, searchText);
        }
        if (compPcodeRad.IsChecked == true)
        {
            return CompanyContains(compDetails.CompanyPcode, searchText);
        }
        return false;
    });
}

at the same time I'd move the condition into a dedicated method and remove nesting by inverting the above if:
private bool CompanyContains(string value, string searchText)
{
    return !string.IsNullOrEmpty(value) && CharactersOnly(value).IndexOf(searchText) > 0;
}


This is a very nice class, and I don't wish to discredit the author (FrinkTheBrave) in any way!  I do, however, want to offer a few enhancements and correct the nasty bugs that are inherent in the original.

The issues/enhancements addressed here:

  o Do not insert duplicates

  o Re-do selection if new row inserted

  o getSelected will return null rather than empty string if nothing selected

  o Proper comparison of string (a.equals(b) rather than a == b)

  o Sort is now case-insensitive

  o Removed 'this.' from this.foo where unneeded (which means, everywhere).

  o Changed setDropDownViewResource as per comment by @seand

To explain more about the re-selection:  Consider the following.  Spinner currently has these items (where > indicates the selected item)

    Antelope
  > Cat
    Dog

Now, we insert Bear.  Unless we re-do it, the second item will remain as 'selected.'  But because we inserted Bear alphabetically, the true Selected item has moved to the third position.

    Antelope
  > Bear
    Cat
    Dog

So, before the insertion of an non-selected String, we will save the String of the current selection (if there is one).  Then, after the insertion and the sort, we will select it again.

    Antelope
    Bear
  > Cat
    Dog

So if I may be so bold....

package c.b.a;

import java.util.Comparator;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class AdvancedSpinner extends Spinner {

    // Thanks to CodeReview: http://codereview.stackexchange.com/questions/491/simplified-android-spinner
    // declare object to hold data values
    private ArrayAdapter<String> arrayAdapter;

    // constructors (each call initialize)
    public AdvancedSpinner(Context context) {
        super(context);
        initialize();
    }

    public AdvancedSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    public AdvancedSpinner(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialize();
    }

    // add the selected item to the end of the list
    public Boolean addItem(String item) {
        return addItem(item, true);
    }

    public Boolean addItem(String item, boolean select) {
        Boolean addFlag = true;

        for (int i = 0; i < getCount(); i++) {
            if (arrayAdapter.getItem(i).equals(item)) {
                // Don't add an item that's already in the list
                // But we do need to mark it as "selected" if
                // applicable.
                addFlag = false;
                if (select)
                    setSelection(i);
                break;
            }
        }
        if (addFlag) {
            String saveSelected = null;
            if (! select) {
                // We need to preserve the prior selection, which may be
                // messed up by our array sort operation.  So we will
                // save the selected item's value, and (after the insert)
                // we will reinstate its selection status.
                saveSelected = getSelected();
            }
            arrayAdapter.add(item);
            setEnabled(true);
            arrayAdapter.sort(new Comparator<String>() {
                public int compare(String object1, String object2) {
                    return  object1.compareToIgnoreCase(object2);
                };
            });
            if (select)
                selectItem(item);
            else if (saveSelected != null)
                selectItem(saveSelected);
        }
        return addFlag;
    }

    // remove all items from the list and disable it
    public void clearItems() {
        arrayAdapter.clear();
        setEnabled(false);
    }

    // make the specified item selected (returns false if item not in the list)
    public boolean selectItem(String item) {
        boolean found = false;
        for (int i = 0; i < getCount(); i++) {
            if (arrayAdapter.getItem(i).equals(item)) {
                setSelection(i);
                found = true;
                break;
            }
        }
        return found;
    }

    public String getSelected() {
        // return the current selected item
        // Changed (Dennis) to return null if nothing selected, rather than the
        // (misleading) empty string.  Also, prior incarnation would ForceClose
        // if array was not empty but nothing was selected.
        String rtnVal = null;
        if (getCount() > 0) {
            int i = super.getSelectedItemPosition();
            if (i >= 0)  // An item has been selected
                rtnVal = arrayAdapter.getItem(i);
        }
        return rtnVal;
    }

    // allow the caller to use a different DropDownView, defaults to android.R.layout.simple_spinner_dropdown_item
    public void setDropDownViewResource(int resource) {
        arrayAdapter.setDropDownViewResource(resource);
    }

    // internal routine to set up the array adapter, bind it to the spinner and disable it as it is empty
    private void initialize() {
        arrayAdapter = new ArrayAdapter<String>(super.getContext(), android.R.layout.simple_spinner_item);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        setAdapter(arrayAdapter);
        setEnabled(false);
    }
}


Please tell me about everything I could do better, but especially how to calculate and not hardcode the randomly shifted second array [...].

I suggest to get a random permutation of [0, 1, 2] by introducing a simple but unbiased shuffle function.

A circular shift of that random permutation can then be found by mapping index i to index (i + shift) % length:

// Return two shifted colors with min, max and random component:
function randomGradientColors(min, max) {
  let permutation = shuffle([0, 1, 2]);
  let shift = random(1, 2);
  return [
    permutation.map(i => [min, max, random(min, max)][i]),
    permutation.map(i => [min, max, random(min, max)][(i + shift) % 3])
  ];
}

Since you asked for everything that you could do better, I would like to suggest using a CSS background gradient instead of a canvas element. If compatibility is not a concern, you can even leverage fancy CSS variables:

.gradient {
  background: linear-gradient(90deg, var(--from, black), var(--to, black));
}

Your markup then would provide the min and max color components via data attributes:

And your script would simply query all .gradient elements and compute their CSS from and to variables from the provided data attributes:

let gradients = document.querySelectorAll(".gradient");
for (let gradient of gradients) {
  let [from, to] = randomGradientColors(
    gradient.dataset.min,
    gradient.dataset.max
  );
  gradient.style.setProperty("--start", "rgb(" + from + ")");
  gradient.style.setProperty("--to", "rgb(" + to + ")");
}

This approach is pretty flexible and allows you to adapt the styling to your needs without touching the script.

Here is the complete code:

// Return random integer within interval [min, max]:
function random(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Shuffle array in-place:
function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

// Return two shifted colors with min, max and random component:
function randomGradientColors(min, max) {
  let permutation = shuffle([0, 1, 2]);
  let shift = random(1, 2);
  return [
    permutation.map(i => [min, max, random(min, max)][i]),
    permutation.map(i => [min, max, random(min, max)][(i + shift) % 3])
  ];
}

// Compute CSS 'from' and 'to' variables for all gradients:
let gradients = document.querySelectorAll(".gradient");
for (let gradient of gradients) {
  let [from, to] = randomGradientColors(
    gradient.dataset.min,
    gradient.dataset.max
  );
  gradient.style.setProperty("--from", "rgb(" + from + ")");
  gradient.style.setProperty("--to", "rgb(" + to + ")");
}
html {
  background-color: #1d1f21;
}

.gradient {
  display: inline-block;
  width: 500px;
  height: 180px;
  background: linear-gradient(90deg, var(--from, black), var(--to, black));
}

.container {
  text-align: center;
}

.textbox {
  text-align: center;
  color: white;
  font-family: monospace;
}

Reload to get a different header gradient.

If you wish to support older browsers, remove the CSS variables and use

gradient.style.background =
  "linear-gradient(90deg, rgb(" + from + "), rgb(" + to + "))";


Comparing pixels against RGB value in NumPy

Your original code can be rewritten as:

mask = np.all(img == (255, 127, 63), axis=-1)

It is a little cleaner, but not more efficient, as it still has to allocate a mask of the same size as the image.


Run the needle program for a query against the subject files and return the result

A very short review, as I don't have the time for a more extensive one.

Enumerate

Some things I see right off the bat is range(len()). Instead of writing this, consider using enumerate. This will allow you to work with any iterable, not just countable, indexable objects.

Unnecessary else

I see this piece of code next:

if needle_output == None:
    return needle_alignment_result = needle_output
else:
    ... code here ...

The else here is unnecessary, as you exit the function after returning in the if. Just move the code in the else right after the if, and remove the unnecessary else, like so:

if needle_output == None:
    return needle_alignment_result = needle_output
... code here ...

is None vs == None

Below is from an amazing StackOverflow answer.

  A class is free to implement
  comparison any way it chooses, and it
  can choose to make comparison against
  None means something (which actually
  makes sense; if someone told you to
  implement the None object from
  scratch, how else would you get it to
  compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare.  But you should use is None as a general rule.

Updated Code

def run_bug():
    """
    The script runs the needle program for a query file against all the
    subject files in a folder and keeps only the highest identity score alignments.
    """
    needle_alignment_result = ''

    query_list_fastafiles, subject_list_fastafiles = start_function()
    files_ending_with_one = filter_files_ending_with_one(subject_list_fastafiles)

    for j, _ in enumerate(query_list_fastafiles):
        initial = 0

        # Take the scaffold sequence one by one
        for i, _ in enumerate(files_ending_with_one):

            # Path of the files
            file1 = query_path + ordered_query_fastafiles[j]
            file1 = subject_path + files[i]
            needle_output = run_needle_two_sequences(file1, file2)

            if needle_output is None:
                return needle_alignment_result == needle_output

            identity_percentage, result_file_as_string = needle_output
            identity_percentage = float(identity_percentage)

            # Keeps the highest percentage result among the files
            if identity_percentage > initial:
                initial = identity_percentage
                needle_alignment_result = result_file_as_string

    write_html(needle_alignment_result)
    return needle_alignment_result


But the second version has problems also because the obj variable is in the global namespace. It might be a good idea to abstract this into a function which contains a reference to the XMLHttpRequest object, and avoids polluting globals as in the first example.

var CurrentTime = function() {
    this.requestObj = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    this.element = document.getElementById("current_time");
};

CurrentTime.prototype.get = function() {
    var self = this;
    this.requestObj.open("GET", "current_time.php", true);
    this.requestObj.send(null);
    this.requestObj.onreadystatechange = function() {
        if (self.requestObj.readyState == 4 && self.requestObj.status == 200) {
            self.element.innerHTML = self.requestObj.responseText;
        }
    };
};

var currentTime = new CurrentTime();
setInterval(currentTime.get.apply(currentTime), 1000);

You could also pass the location of the PHP file to this CurrentTime function for further abstraction, however I think this is good as is. The apply method is used to set the context of the method to the currentTime variable and not the window, so that you don't get TypeErrors. :)


It is not just the safety of your code that you should be worried about. You need a holistic approach; your question suggests to me that you have not looked at the bigger picture. Read this article and you will see you need to approach your question differently. For one, it depends on your server's configuration.

Depending on how important the security requirements are for you, I'd suggest using a third party service; either one which takes the problem off your hands entirely, or if that's not an option, have a consultant guide you to making a setup that will stay secure even over time while code changes and cracks can slip through unnoticed. There are some services that can try to find holes in your system, but they are only of limited use.

If you need a better answer than this, I think you're going to have to give a lot more info on the context of your code; where it's used, how it's used, etc.


Find minimum count of items where sum of them is X from an array

Naming

Your function does not return “minimum elements,” but the shortest subset of an array with a given sum. I would suggest something like

func shortestSubset(of array: [Int], withSum goal: Int) -> [Int]

Handling exceptional cases

Your code returns the entire array if no subset with the given sum exists, which seems not sensible to me.

In a comment you said that it should return an empty array in that case, but that would be ambiguous: an empty array is also the correct result for goal = 0.

The Swift way would be to make the result an optional which is nil if no subset is found:

func shortestSubset(of array: [Int], withSum goal: Int) -> [Int]? {
    let subsets = array.allSubsets

    let validSubsets = subsets.filter { subset in
        subset.reduce(0, +) == goal
    }

    if let firstValid = validSubsets.first {
        return validSubsets.dropFirst().reduce(firstValid) { $0.count < $1.count ? $0 : $1 }
    } else {
        return nil
    }
}

Note also that the + operator can be passed directly to the closure parameter of reduce() which reduces(!) the code slightly.

Performance: avoid creation of intermediate arrays

The first performance problem is that a list with all subsets is generated first. For an array with \$ N \$ elements that makes \$ 2^N \$ subsets.

A better approach would be to determine the shortest subset while enumerating the subsets, instead of putting all subsets into a list first. Here is a first attempt:

// Version A:

func shortestSubset(of array: [Int], withSum goal: Int) -> [Int]? {
    // Terminating condition:
    guard let first = array.first else {
        return goal == 0 ? [] : nil
    }

    // Recursion:
    let tail = Array(array.dropFirst())
    let subsetWithout = shortestSubset(of: tail, withSum: goal)
    let subsetWith = shortestSubset(of: tail, withSum: goal - first)

    switch (subsetWithout, subsetWith) {
    case (let s1?, let s2?): return s1.count < s2.count + 1 ? s1 : [first] + s2
    case (let s1?, nil): return s1
    case (nil, let s2?): return [first] + s2
    case (nil, nil): return nil
    }
}

In the recursion step, the shortest subsets which can be obtained by including or omitting the first array element are determined recursively. The switch-statement is used to handle the case where none, one, or both of these intermediate results are nil.

This turned to be a bit faster in my tests, but there are still many intermediate array created at

let tail = Array(array.dropFirst())

If we modify the method to take a collection of integers instead of an array then we can pass the slice array.dropFirst() directly to the recursive call. Slices are “cheap” to create and share the storage with their origin (unless mutated):

// Version B:

func shortestSubset<C: Collection>(of array: C, withSum goal: Int) -> [Int]? where C.Element == Int {
    // Terminating condition:
    guard let first = array.first else {
        return goal == 0 ? [] : nil
    }

    // Recursion:
    let subsetWithout = shortestSubset(of: array.dropFirst(), withSum: goal)
    let subsetWith = shortestSubset(of: array.dropFirst(), withSum: goal - first)
    switch (subsetWithout, subsetWith) {
    case (let s1?, let s2?):
        return s1.count < s2.count + 1 ? s1 : [first] + s2
    case (let s1?, nil):
        return s1
    case (nil, let s2?):
        return [first] + s2
    case (nil, nil):
        return nil
    }
}

This turned out to be considerably faster in my test.

Performance: prune the search tree

A possible performance improvement is to stop the recursion if the goal cannot be reached with the remaining array elements, i.e. if the target sum is smaller than the smallest possible sum or larger than the largets possible sum of the array.

Here it is useful to do the recursion in a helper function. The main function computes the smallest and largest sum once and passes it on to the helper function. The helper function can update those limits, without the need of computing them again.

The helper function takes an array slice as argument, that is another way to void the creation of intermediate arrays.

// Version C:

func shortestSubsetHelper(of array: ArraySlice<Int>, withSum goal: Int,
                          min: Int, max: Int) -> [Int]? {
    guard let first = array.first else {
        return goal == 0 ? [] : nil
    }
    if goal < min || goal > max {
        return nil
    }
    let subsetWithout = shortestSubsetHelper(of: array.dropFirst(), withSum: goal,
                                         min: min, max: max)
    let subsetWith = first < 0 ?
        shortestSubsetHelper(of: array.dropFirst(), withSum: goal - first,
                              min: min - first, max: max) :
        shortestSubsetHelper(of: array.dropFirst(), withSum: goal - first,
                              min: min, max: max - first)
    switch (subsetWithout, subsetWith) {
    case (let s1?, let s2?):
        return s1.count < s2.count + 1 ? s1 : [first] + s2
    case (let s1?, nil):
        return s1
    case (nil, let s2?):
        return [first] + s2
    case (nil, nil):
        return nil
    }
}

func shortestSubset(of array: [Int], withSum goal: Int) -> [Int]? {

    let smallestSum = array.filter { $0 < 0 }.reduce(0, +)
    let largestSum = array.filter { $0 > 0 }.reduce(0, +)
    return shortestSubsetHelper(of: array[...], withSum: goal,
                                min: smallestSum, max: largestSum)
}

Dynamic programming

What we have here is a variant of the “subset sum problem”, which has well-known solutions using dynamic programming. Instead of determining only if a subset with the given sum exists we also need the smallest subset with that sum.

The following is motivated by the “Pseudo-polynomial time dynamic programming solution” from the above Wikipedia article. We maintain a dictionary which for every achievable sum stores the shortest subset with that sum that has been found so far. The given array is traversed once, and the dictionary updated accordingly for each array element.

// Version D:

func shortestSubset(of array: [Int], withSum goal: Int) -> [Int]? {
    // Map each possible sum to the shortest subset found so far with that sum:
    var dp: [Int: [Int]] = [0: []]

    for elem in array {
        let upd = dp.map { (key, value) in (key + elem, value + [elem])}
        for (key, value) in upd {
            if let oldValue = dp[key] {
                if value.count < oldValue.count {
                    dp[key] = value
                }
            } else {
                dp[key] = value
            }
        }
    }
    return dp[goal]
}

This turned out to be faster for large arrays.

Benchmarks

The following (very simple) benchmark was done on a 3.5 GHz Quad-Core Intel Core i5 iMac running macOS 10.15, and

let array = [1, -2, 3, -4, 5, -6, 100, 100, 7, -8, 9, -10, 11, -12]
let goal = 20

let start = Date()
let result = shortestSubset(of: array, withSum: goal)
let end = Date()
print(result, end.timeIntervalSince(start) * 1000)

compiled with Xcode 11.3.1 in Release mode, i.e. with optimization.

Results (approximately):

Original code: 6 milliseconds.
Version A: 3 milliseconds.
Version B: 0.7 milliseconds.
Version C: 0.2 milliseconds.
Version D: 0.4 milliseconds.

With the larger array

let array = [1, -2, 3, -4, 5, -6, 100, 100, 7, -8, 9, -10, 11, -12,
             1, -2, 3, -4, 5, -6, 100, 100, 7, -8, 9, -10, 11, -12]
let goal = 20

we get the following results:

Original code: ???
Version A: 37733 milliseconds.
Version B: 6079 milliseconds.
Version C: 548 milliseconds.
Version D: 2.5 milliseconds.


You can simplify it to this:

def reorder_ordereddict(od, new_key_order):
    new_od = OrderedDict([(k, None) for k in new_key_order if k in od])
    new_od.update(od)
    return new_od

The first line establishes the required key order, being careful not to introduce keys that don't already exist.

The second line takes care of the rest.  The existing keys not explicitly mentioned should come out in the correct order when update() iterates through the keys of od.