class Pool(type):

The defaultdict class will automatically create my list when I access it

    pool = collection.defaultdict(list)

The python style guide suggests using the form class_ rather then clas
It is also not clear why you are capturing the incoming arguments as variable.
This being a metaclass it is going to have consistent parameters

    def __new__(class_, name, bases, classdict):
        def __del__(self):

Since pool now automatically creates the list, we can just append to it
                Pool.pool[self.class].append(self)

Getting rid of the variable arguments also makes this much clearer.

        classdict['__del__'] = __del__
        return type.__new__(class_, name, bases, classdict)

args and kwargs are often used as the names for variable parameters. I recommend using them to make code clearer

    def __call__(class_, *args, **kwargs):

Thanks to the use of defaultdict above we can make this code quite a bit cleaner. Also, this code doesn't pretend its using a functional programming language. Your code created lists by adding them together, slicing, etc. That is not a really efficient or clear way to use python.

        instances = Pool.pool[class_]
        if instances:

There is a subtle and dangerous problem here. When you create a new instance, you pass along your parameters.
However, if an instance is already created, you return that ignoring what the parameters were doing.
This means that you might get an object back which was created using different parameters then you just passed.
I haven't done anything to fix that here

            print('Pool.pool is not empty: return an already allocated instance')
            return instances.pop()
        else:
            print('Pool.pool is empty, allocate new instance')
            return type.__call__(class_, *args, **kwargs)

Your technique is to install a __del__ method on the objects so that you can detect when they are no longer being used and keep them in your list for the next person who asks for them. the __del__ method is invoked when the object is about to be deleted. You prevent the deletion by storing a reference to the object in your list. This is allowed but the python documentation indicates that it is not recommended.

__del__ has a number of gotchas. If an exception is caused while running the __del__ method it will be ignored. Additionally, it will tend to cause objects in references cycles to not be collectable. If your code is ever run on Jython/IronPython then you can't be sure that __del__ will be called in a timely manner. For these reasons I generally avoid use of __del__.

You are using a metaclass so the fact that the given object is pooled is hidden from the user. I don't really think this is a good idea. I think it is far better to be explict about something like pooling. You also lose flexibility doing it this way. You cannot create multiple pools, etc.

The interface that I would design for this would be:

pool = Pool(Foo, 1, 2, alpha = 5) # the pool gets the arguments that will be used to construct Foo
with pool.get() as f1:
    # as long as I'm in the with block, I have f1, it'll be returned when I exit the block
    f1.foo()
with pool.get() as f2:
    f2.foo()
    with pool.get() as f3:
        f3.foo()

f4 = pool.get()
f4.foo()
pool.repool(f4)


I would split the if to 3 variables and give each a name : out of image,  isVisited and isOriginalColor or something similar.

I don't know what sr means, I would use row and col.

FloodFill return image  but dfs change the original image, It can confuse the user of the class.


var isAlpha = function(char){
    return typeof char==="string" && char.length == 1 && char <= "Z" && char >="A";
};

I like this. I like the careful type and length checking, and the comparison with strings rather than weird numeric codes. I would suggest first that it could do with handling lower case letters as well. Second, it seems like a moderately useful general purpose function, and not something that can only be used within the scope of a rot13 call. I'd be inclined to move it out.

Your main case analysis works (Except for not handling lower case numbers) but it could probably be clearer.
I would suggest

if(isAlpha(str[i])) {
    if (str[i].charCodeAt() < 78) {
        ...
    } else {
        ...
    }
} else {
    ...
}

This makes it clear that you have handled every possible case. In my opinion it also makes it clearer what the structure of the conditional is.

It would be even clearer what you're testing if 78 wasn't sitting there as a magic number. Using "N".charCodeAt() or even better "A".charCodeAt() + 13 would help. If concerned about the performance penatly of doing the extra function call in the check, make it a constant outside the loop.

var shifted = [];
var decoded= [];

I would suggest that you preallocate the length of your decoded array to be the length of your input string. This improves efficiency because Javascript knows to pack it tightly, and knows exactly how big it is going to get. It also improves readability by providing contextual clues. (i.e. that it's associated with str

I would completely delete shifted. You don't need an array to hold on to intermediate values that are immediately finished and placed in decoded. If you don't want to put the whole thing into one line, use a single scalar variable instead of an array.

// Change the inputs below to test
rot13("SERR PBQR PNZC");

It is good to test code! And it's nice when CodeReview questions actually come with evidence of testing too. I would suggest that a slightly more pedantic test case might be suitable. I'd want to use something with all classes of characters: upper & lower case, numbers, spaces, and assorted symbols. In particular I'd make sure that the test case contains both "A" and "Z" as well as  "@" and "[" These are just outside of the letters range in ASCII, so good for checking for Off By One errors. It would also be quite nice to express the target output so that we know whether it's worked!

(In a proper testing framework that would be in code, but a comment probably suffices here.)

In terms of naming, it broadly seems fine. I would probably choose a different name for str, possibly cipherText.

In terms of formatting things are a bit all over the place. I don't have strong opinions on JavaScript formatting style, but whatever style you pick it's worth sticking to consistently. Personally there are too many blank lines for my liking; in particular a blank line between the end of an if clause and its associated else clause is really jarring!


You can take advantage of C#'s variable parameter arguments (keyword params). Like this -

public DataSet GetDataSource(string fillBy, string server, params KeyValuePair<String, Object>[] parameters)
    {
        string query = GetQuery[fillBy];
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = GetSqlConnection[server];
        SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
        foreach (KeyValuePair<String, Object> p in parameters)
        {
            adapter.SelectCommand.Parameters.AddWithValue("@" + p.Key, (p.Value.ToString().Length == 0) ? DBNull.Value : p.Value);
        }
        DataSet dataSet = new DataSet();
        dataSet.Tables.Add(new DataTable());
        adapter.Fill(dataSet.Tables[0]);
        return dataSet;
    }

params is the keyword to use for taking variable numbers of arguments. Then you can just call it with variable arguments like -

   dataGridView.DataSource = dataSource.GetDataSource(fillBy, server,
        new KeyValuePair<string, object>("findBy",findByTextBox.Text)
        ).Tables[0];

and in another time you can call same function with -

   dataGridView.DataSource = dataSource.GetDataSource(fillBy, server,
            new KeyValuePair<string, object>("findBy",findByTextBox.Text),
            new KeyValuePair<string, object>("findBy2",findByTextBox2.Text)
        ).Tables[0];

This will atleast save you from defining a dictionary all the time.


Algorithm

Your current method relies on iterating through all numbers and checking if they're 1) a factor 2) prime.

With the new algorithm, not only are we able to skip the expensive primality check, but we're also able to reduce our search space massively (the upper bound is the square root of the number).

public static long maxPrimeFactor(long n) {
    long factor = -1;
    for (int i = 2; i * i <= n; i++) {
        if (n == 1) { break; }
        if (n % i != 0) { continue; }
        factor = i;
        while (n % i == 0) {
            n /= i;
        }
    }
    return n == 1 ? factor : n;
}

This algorithm is a slightly optimized version of Martin R's answer.

We first "trim" down a number by repeatedly dividing it by factors of itself which are smaller or equal to its square root. Here're some examples

[3] (no factors <= sqrt(3))
[4 -> 2 -> 1] (factors: 2)
[200 -> 100 -> 50 -> 25] --> [5 -> 1] (factors: 2, 5)
[7007 -> 1001 -> 143] --> [13] (factors: 7, 11. 13 > sqrt(143), hence it stops)

The square brackets represent groups of "divisions" where a number is repeatedly divided by the factor.

Most composite numbers will be reduced down to 1. This is because all prime factors of a composite number will always be lower than or equal to its square root. However, note that as an optimization, we trim down the upper bound to the square root of the new number upon every iteration. This results in a few cases where we stop at a prime number. In that case, we return that number, which is the largest prime factor.

Note that we only need to iterate through primes. Since a prime sieve is too expensive, iterating through {2, 3, 5, 7, ..., sqrt(n)} works well enough for our scenario. For clarity, my code iterates through all integers from 2 to sqrt(n); I'll leave this to the OP as an exercise.

Benchmarks

In these benchmarks, my algorithm refers to the optimized version of the algorithm, as mentioned in the previous paragraph.

OP's algorithm:

Result: 6857
Time required to calculate in nanoseconds: 870707572

h.j.k.'s algorithm:

Result: 6857
Time required to calculate in nanoseconds: 864074780

Slight improvement there, but not much.

JS1's algorithm:

Result: 6857
Time required to calculate in nanoseconds: 10038730

A definitely massive improvement, but is still a bit slow since the primality tests are too slow.

thepace's algorithm is currently a WIP.

From thepace's algorithm onwards, the benchmarks run too fast to be effective. Using 1000 trials:

Algorithm: wei2912's algorithm
Average time per trial (ns): 15507
Algorithm: Alnitak's algorithm
Average time per trial (ns): 10880

Looks like Alnitak's algorithm is faster.

1000000 random ints

Generating a million random ints and feeding them in:

Algorithm: wei2912's algorithm
Average time per trial (ns): 12337
Algorithm: Alnitak's algorithm
Average time per trial (ns): 7661

Alnitak's algorithm appears to be nearly 2 times faster. Great job to Alnitak! :)

I'd be glad to accept any suggestions for benchmarks.

My original solution in Haskell is as follows:

module Main where

intSqrt :: Integer -> Integer
intSqrt = floor . sqrt . fromIntegral

maxPrimeFact :: Integer -> Integer
maxPrimeFact n = go n 1 (2 : [3, 5..intSqrt n])
  where
    go 1 maxPrime _ = maxPrime
    go n _ [] = n
    go n maxPrime wheel@(w:ws)
        | m == 0 = go d w $ takeWhile (<= intSqrt d) wheel
        | otherwise = go n maxPrime ws
        where
            (d, m) = n `divMod` w

problem3 :: Integer -> Integer
problem3 = maxPrimeFact

main :: IO ()
main = do
    _ <- getLine
    contents <- getContents
    let cases = map read $ lines contents
    let results = map problem3 cases
    mapM_ print results

Credit must go to Martin R for the original solution.


Notify observers when object attributes update

To give you valuable feedback on your usecase, I would need more information, like: How do listeners listen? How does the caller look like?

How exactly does _flightSearchRequestModelLiveData.value = this notify all listeners of live data? Its not a function call, so how is an event created and pushed?!

Instead I will give some pattern advices you may need.

Use constructor initialisation

Kotlin enables you to set fields over constructors. Even if your class is a singleton and all values are default - creating a constructor will enable to test your class easily (and other benefits).

So instead of:

class FlightSearchManager {

    private val _flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData()
    val flightSearchRequestModelLiveData : LiveData<FlightSearchRequestModel> get() = _flightSearchRequestModelLiveData

    var flightSearchRequestModel : FlightSearchRequestModel

try to go for:

class FlightSearchManager(
    val flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData(),
    var flightSearchRequestModel : FlightSearchRequestModel = FlightSearchRequestModel()
) {

If you already have a constructor for a class and it is valid to have all fields to have default values - don't force the caller to set them!

This code is an anti-pattern:

flightSearchRequestModel =
            FlightSearchRequestModel(
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null)

What you should go for would be:

data class FlightSearchRequestModel(
   val propertyOne : String? = null,
   val propertyTwo: Int? = null,
   ...
)

FlightSearchManager {
  val model = FlightSearchRequestModel()
}

Parameters

It is seen as code smell, when your method has too many parameters, so I would recommend to reduce the number of those in fun updateFlightSearchRequestModel.

You could create a single function for every parameter change. Of course it means more lines to write, but is cleaner, straight forward and not as error-prone to side effects since you don't change ~20 things in one method.

Naming convetions

I would guess that you coded with something like C# before, because of the usage of underscores _ in variable names. Please try to follow the appropreate convetion for this language (Kotlin), as well as in Java:

  Local variables, instance variables, and class variables are also written in lowerCamelCase. Variable names should not start with underscore (_) or dollar sign ($) characters, even though both are allowed. This is in contrast to other coding conventions that state that underscores should be used to prefix all instance variables.

Constants:

  Constants should be written in uppercase characters separated by underscores. Constant names may also contain digits if appropriate, but not as the first character.

Source

Fields like this:

private val _flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData()

would become:

private val flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData()

Functions like this

fun updateFlightSearchRequestModel(_arriveAirport : String? = null,
                                   _arriveAirportId: Int? = null,

would become:

fun updateFlightSearchRequestModel(arriveAirport : String? = null,
                                   arriveAirportId: Int? = null,

Immutability

Immutable code is easier to debug, to understand and to test. Favor val over var in (almost) every case.

If you really need to change something by reference, at least create a completely new immutable object. Example:

This

flightSearchRequestModel.apply {
            arriveAirport = _arriveAirport ?: arriveAirport
            arriveAirportId = _arriveAirportId ?: arriveAirportId
            ...
}

could become this:

flightSearchRequestModel = copy(arriveAirport = arriveAirport, arriveAirportId  = arriveAirportId, ...)


UrlRouter which uses regular expressions to find out what to do

The first improvement you definitely want is capturing groups. These groups allow you to get rid of splitting at "/" and working on magic indices and instead use a Matcher to extract the parts from a matched string.

This greatly simplifies your delegating methods that work on a String to using the Matcher instance you used and threw away in your if-condition:

private void showPage(Matcher url) {
    postController.showPage(url.group(1));
    // alternatively use
    postController.showPage(Integer.parseInt(url.group(1)));
}

This would only require minor changes for your regexes:
You'd need to enclose the captured groups in parentheses as follows.

private final static String pageRegex = "/page/(\\d{1,5})";
private final static String yearRegex = "/(\\d{4})";
private final static String monthRegex = "/(\\d{1,2})";
private final static String nameRegex = "/([a-z0-9\\-]+)";


Structured instructions for simple extraction script

This is how I would implement it:

#!/usr/bin/perl
use warnings;
use strict;

my $file = 'input.dat';
open my $IN, '<', $file or die $!;

my $uniq;
while (my $line = <$IN>) {
    next unless $line =~ /^\s*keyword123/;
    if (defined $uniq and $line ne $uniq) {
        die "Entry not unique. Exiting.\n";
    }
    $uniq = $line;
}
$uniq =~ s/.*\((.*)\).*/$1/;
$uniq =~ s/\s.*//;
print "keyword123: $uniq";

You can check the uniqueness each time you read the keyword line in. Once you find a non-unique line, you can stop right at the moment, no need to search the rest of the file.


You're vastly overcomplicating the solution by introducing three arrays heightTracker, planeTracker, and newArray.  None of those is needed: just track the elevation (which is a better name than height), and go by the definition:

  A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

So, the number of valleys traversed is the number of times Gary's elevation changes from -1 to 0.

function countingValleys(n, s) {
    let elevation = 0;
    let traversedValleys = 0;
    for (let i = 0; i < n; i++) {
        if (s[i] === "D") {
            --elevation;
        } else if (s[i] === "U") {
            if (++elevation === 0) traversedValleys++;
        }
    }
    return traversedValleys;
}


Generalizing code to write less of it

Adding support for a new time scale

To test your code for maintainability let's go through a hypothetical situation. What if a new temperature scale were introduced - say Felsius?

To add support for the up-and-coming scale you would need to add a new file, felsius.js, which will contain 3 conversion functions: toKelvin toCelsius toFahrenheit. Next add toFelsius functions in each of the existing temperature scale files.

Alright, lots of maths... but awesome. We did it! Now simply to add:

let fromFelsius = (value) => {
  const conversion = require('./felsius');
  let celsius = fixFloat(conversion.toCelsius(value));
  let fahrenheit = fixFloat(conversion.toFahrenheit(value));
  let kelvin = fixFloat(conversion.toKelvin(value));
  return `${value}°ϵ = ${celsius}°F = ${fahrenheit}°F = ${kelvin}K`;
};

And add:

let felsius = fixFloat(conversion.toFelsius(value));
`${felsius}°ϵ`;

To each fromX function.

Finally done! Let's reflect:

  Hmmmm... That seemed like an awful lot of work - possibly prone to errors too.

Unfortunately we don't have time for any more reflection because the project manager just informed us of a huge user base that firmly believes in the Rankine scale.

Possible modification

Having a specialized conversion function between each temperature scale requires \$n^2\$ conversion functions (where \$n\$ is the number of temperature scales you support). You could get by with \$2n\$ if you used a standard temperature scale as the root of all of your conversions. For example fahrenheit.js using Celsius as the standard:

'use strict';

let fromCelsius = (value) => (value * (9 / 5)) + 32;
let toCelsius = (value) => (value - 32) * (5 / 9);
let toString = (value) => `{value}°F`

module.exports = {
  fromCelsius,
  toCelsius,
  toString,
};

Now convert.js

'use strict';

let fixFloat = (value) => parseFloat(value).toFixed(2);

const temperatureScales = [
  {
    name: 'Fahrenheit',
    file: './farhenheit.js'
  },
  {
    name: 'Celsius',
    file: './celsius.js'
  },
  {
    name: 'Kelvin',
    file: './kelvin.js'
  },
  {
    name: 'Felsius',
    file: './felsius.js'
  },
];

// add conversion code for each temperature scale
module.exports = temperatureScales.reduce((m, fromScale) => {
  const fromTemp = require(fromScale.file);

  // generate the `fromFooBar` function
  m['from' + fromScale.name] = (value) => {
    const standard = fromTemp.toCelsius(value);

    let str = fromTemp.toString(fixFloat(value));

    // generate the rest of the result string
    return temperatureScales.reduce((str, toScale) => {
      if (toScale == fromScale) { // don't recompute the initial temperature
        return str;
      }

      const toTemp = require(toScale.file);
      const temperatureValue = fixFloat(toTemp.fromCelsius(standard));
      const temperatureString = toTemp.toString(temperatureValue);
      return str + " = " + temperatureString;
    }, str);
  };

  return m;
}, module.exports);

Eliminating some of the redundancies makes it much easier to add Rankine support. Simply add { name: 'Rankine', file: './rankine.js' } to the temperatureScales list. Then add three functions: toCelsius fromCelsius toString to ./rankine.js.

Often redundancies in code lead to more work when maintaining. However, the generalized code might be less readable than the redundant version (nested reduce functions - why would anyone do that??).

Nice work overall! For your purpose the redundancies are probably fine -- just some food for thought.


It depends what direction you want to go with your program, but my suggestion would be to make small factories for components you use the most often. Here it seems you are building a common UI feature: a form with several fields. Since you only have a single form you don't really benefit from abstracting the form for now, except for clarity, but you benefit from abstracting the fields as you use 4 of them.

So this code separates better generic UI components and data although it's not perfect; but UI code rarely is. Since you usually only have a handfew windows in the average app it's often OK to hardcode some values and components. It's a matter of making compromises between genericity, features, and verbosity.

(Disclaimer: I haven't tested it, please let me know if it needs fixing)

class FormField:
    def __init__(self, window, row, label, placeholder=None):
        tk.Label(window, text=label).grid(row=row)
        self.entry = tk.Entry(window)
        self.entry.grid(row, column=1)
        if placeholder:
            self.entry.insert(0, placeholder)

    def get(self):
        return self.entry.get()

class Form:
    def __init__ (self, window, row, field_keywords, callback, button_text):
        self.fields = []
        for i, field_keyword in enumerate(field_keywords):
             self.fields.append(window, row=row + i, **field_keyword)
        self.callback = callback
        # This '10' is hardcoded, but you could compute it from button_text length
        b_apply = tk.Button(window, text=button_text, width=10, command=self.submit))

    def submit(self):
        self.callback(*[field.get() for field in self.fields])

def init_ui(window, root_dir):
    # Below is code that is tricky to make any more generic and can be left as is
    # Making UI abstractions for single use components can be complexity you don't need
    window.title('ACFA Save Editor')
    messagebox.showinfo('Open Save Folder', 'Ex: GAMEDATXXXX')
    directory = askdirectory(initialdir=root_dir)
    APGD = directory + '/APGD.dat'
    GAMEDAT = directory + '/' + directory.split('/')[-1] + '_CONTENT'
    p, a, c, f = read_data(APGD)
    fields_kws = [{'label':'Pilot name: ', 'placeholder':p},
                  {'label':'AC name: ', 'placeholder':a},
                  {'label':'COAM (money): ', 'placeholder':c},
                  {'label':'FRS Memory: ', 'placeholder':f}]
    ui_form = Form(window, 1, field_kws, lambda p, a, c, f: apply(p, a, c, f, APGD, GAMEDAT), 'Apply')

    b_quit = tk.Button(window, text='Quit', width=10,
        command=window.destroy).grid(row=4, column=1)
    return window


First I'd like to mention a style point. Ditch the hungarian notation. You don't need it. It often isn't maintained, so they tend to lie. when they are, it's a bit of a pain to find/replace your variable names. sReader should just be reader, intCount should just be count and so on.

I like that you're taking advantage of the single line variable declaration & assignment.

You should be using a few constants for your data file though. This reduces code duplication and makes it easier to change down the road.

const dataFilePath As String = "C:\MyProject\"
const dataFileName As String = "Hardware.txt"
const dataFile As String = dataFilePath & dataFileName

Now your code would look like this.

If IO.File.Exists(dataFile) Then     ' Make sure the file exists
    reader = New IO.StreamReader(dataFile)
Else
    '....

I don't see anything inherently wrong about your method of processing the file line by line. It's essentially no different from working in a 2 dimensional array. You may want to find out if you can read the whole file at once and use one anyway. I bet there would be a performance benefit.

What I do notice about your loops is the heavy reliance on Magic Numbers.

Go ahead and declare another constant TabChar and set it equal to Chr(9).
And here:

        If intFullLoop > 14 And intCount > -1 And CBool((intCount - 0) / 11 Mod 0) Then
            cmbSelectHinge.Items.Add(sMyStrings(intCount))
        End If

What is 14? What is 11? Find appropriate names for them. It makes your code easier to read and easier to change/maintain later.

Further Reading on Naming Conventions


Returning substrings (motifs) and original strings (sequences) from a file of strings (sequences)

Disclaimer: I know very little about bioinformatics, so I’m reviewing this on the quality of the Python code. I’m not qualified to comment on the scientific accuracy.

So here are a few suggestions:

You need better comments and documentation.  Ideally a docstring on the function(s), and some more comments that explain why the code was written this way – how does it relate to the underlying scientific principles? As it stands, it’s fairly opaque, and so it would be hard to another scientist to verify that it’s a correct implementation.

As a sidebar to this, you should pick much better variable names as the inputs to your function – a, b and c are utterly useless. Likewise the function name isn’t very helpful – lots of functions compute something, but what does this function compute?

Perhaps something like:

def gen_uniq_subsequences(index_5p, motif_size, mirna_list):

More characters, but substantially easier to read.
The output isn’t a particularly useful format. You’re returning a list of strings, which is fine for printing, but what if somebody wants to get the individual components of those results. Say, break out the position and the motif separately from the record ID?

I’d have this function return some chunk of structured data (say, a namedtuple), and then the pretty printing goes off to a separate function. Makes it much easier to reuse the outputs of this function.

Which leads me to my next comment…
Your function is doing too much work.  Ideally a function should have a single responsibility, an action that can be described in a single sentence. But your function does quite a lot:

Unpacks the third input from a string into a set.
Opens the sorted.human.mature.fa file, and starts parsing it.
Constructs the results list, which is some sort of scientific computation.
Assembles that into rigid strings for pretty-printing.

Most of those actions don’t need to be in this function – pushing them out will allow you to simplify this part of the code, which makes it easier to review, read and maintain.

For example, suppose I already have a set that contains my miRNAs. It would be much cleaner if I could pass that in directly, rather than packing it into a string so that you can unpack it again.
You can simplify your looping constructs. Two places immediately jump out at me:

You don’t need the else: continue; if you omit this the you get the same behaviour.
If you slightly rearrange the while loop and add a break, you can get rid of the flag_motif_unique sentinel variable.

Neither of these are ground-breaking, but they make your code a bit easier to write.


Langton's Ant cellular automaton in Ruby

The code looks pretty clean. On first sight I notice some odd Ruby code.

Non-idiomatic Ruby

class Tile
    @state = State::OFF
    def initialize(state)
        @state = state
    end
    def state
        return @state
    end
    def flip
        if @state == State::OFF
            return @state = State::ON
        else
            return @state = State::OFF
        end
    end
    def bool
        return (@state == State::ON ? true : false)
    end
end

In the code above you first set @state and then inside initialize you set @state again. These two are not the same variable. Do not define instance variables outside class methods, unless you want to do some meta-programming with them.

You define method state for accessing the @state variable. As this is such a common pattern, Ruby provides a helper for generating such simpler getter methods:

class Tile
    attr_accessor :state

But all the places where state method is used, could actually use the bool method instead. This should make one realize that this whole Tile class could be completely eliminated and replaced with a plain boolean value instead.

Other smells

Screen class has @screen instance variable. It's not referring to itself, so a better name would be in order.
It's also exposing it directly to the outside world through screen method. Better to have a method like get(x,y) that would encapsulate the access to the coordinates array.
Screen has an inspect method that's unused. For debugging?
Screen has x and y fields, I think these are better called width and height.
Screen has a print method. I would instead recommend having a to_s method instead, so the Screen would not have a knowledge about printing itself, only of how to convert itself into string. One can then simply call puts screen to print it to console (the to_s method will be call automatically when casting to string).
Inside Ant.initialize all the variables are initialize on the same line, which I find confusing.


There isn't much to refactor here and you already identified the problem scope.

You are much better off with a JavaScript template engine.

I won't be too opinionated here, but popular options are:

http://handlebarsjs.com/
https://github.com/janl/mustache.js/
http://documentcloud.github.io/underscore/#template
http://ejohn.org/blog/javascript-micro-templating/


Dictionary of key signatures for various major and minor scales

As with many programming problems, this one can be solved with an extra layer of indirection.  As you know, the sharps and flats are added in a predictable order (the circle of fifths).  A highly compressed way to describe a key signature is to state how many sharps or flats there are.  Here, I'll choose to encode sharps as positive numbers, and flats as negative numbers.  I'll also write it using a two-column layout.

SCALES = {
    'do bemol mayor': -7,           'la bemol menor': -7,
    'sol bemol mayor': -6,          'mi bemol menor': -6,
    're bemol mayor': -5,           'si bemol menor': -5,
    'la bemol mayor': -4,           'fa menor': -4,
    'mi bemol mayor': -3,           'do menor': -3,
    'si bemol mayor': -2,           'so menor': -2,
    'fa mayor': -1,                 're menor': -1,
    'do mayor': 0,                  'la menor': 0,
    'sol mayor': +1,                'mi menor': +1,
    're mayor': +2,                 'si menor': +2,
    'la mayor': +3,                 'fa sostenido menor': +3,
    'mi mayor': +4,                 'do sostenido menor': +4,
    'si mayor': +5,                 'sol sostenido menor': +5,
    'fa sostenido mayor': +6,       're sostenido menor': +6,
    'do sostenido mayor': +7,       'la sostenido menor': +7,
}

The trick, then, is to write some code to perform a lookup using that data structure.  Here's how I would do it:

KEY_SIGNATURE_DECODERS = (
    lambda n: ['ninguna'],
    lambda n: ['fa♯', 'do♯', 'sol♯', 're♯', 'la♯', 'mi♯', 'si♯'][0:+n],
    lambda n: ['si♭', 'mi♭', 'la♭', 're♭', 'sol♭', 'do♭', 'fa♭'][0:-n],
)

def key_signature(scale):
    """
    Given the name of a major or minor scale in Spanish (e.g. "re mayor"),
    return a list of the sharps or flats in its key signature.
    For C Major and A Minor, return a one-element list containing
    the string "ninguna".
    """
    def signum(n): return -1 if n < 0 else +1 if n > 0 else 0
    count = SCALES[scale]
    return KEY_SIGNATURE_DECODERS[signum(count)](count)

Note that I would divide the work between the search() and main() functions differently, such that one function is purely responsible for the lookup, and the other serves as the user interface (prompting, formatting, and looping).

def main():
    print("Bienvenido al buscador de armaduras por Jfelix\n"
          "Escriba 'quit' cuando termine de buscar.")
    while True:
        scale = input('Escriba la tonalidad para encontrar su armadura: ')
        scale = scale.lower()
        if scale == 'quit':
            break
        try:
            print('La armadura de {0} es: {1}'.format(
                scale,
                ', '.join(key_signature(scale))
            ))
        except KeyError:    # Ha ha, KeyError -- get it?
            print('¿Estas seguro que esa es una tonalidad?')

if __name__ == '__main__':
    main()


Refactor the code which performs "cross-product", "reduce", "product of list" and "sum of list"

One immediate improvement is realizing that for e.g the input 14 7, all combinations like x x x x x x 9 and above can never sum to 14, because even for the minimal case x = 1, 9 + 6*1 = 15. So you can vastly reduce the number of combinations you need to check by using

k = {i for i in combinations_with_replacement(range(1, x - y + 2), y) if sum(i) == x}

For the input 14 7 this constitutes a difference of 77520 possible combinations down to 3432.

This adds a constraint only on the last number, but you could take this to its logical extreme and write code that always aborts the combinations once the sum has been reached.

One other thing you should do is use better names and use functions. I have no idea that k is a list of combinations of numbers, or what this means. Also, using i (and j, k, n, too, for that matter) for anything other than an integer is not helpful either.

I would at least rewrite your code to this:

from itertools import combinations_with_replacement
try:  # Python 3.8+
    from math import prod
except ImportError:
    from functools import reduce
    from operator import mul
    def prod(x):
        """Returns the product of all elements of `x`, similar to `sum`."""
        return reduce(mul, x, 1)

def maximum_product_with_sum(x, n):
    """Return the maximum product of all `n` positive numbers that sum to `x`."""
    r = range(1, x - n + 2)
    candidates = {candidate
                  for candidate in combinations_with_replacement(r, n)
                  if sum(candidate) == x}
    return max(map(prod, candidates), default=1)

if __name__ == "__main__":
    for _ in range(int(input())):
        x, n = tuple(map(int, input().split()))
        print(maximum_product_with_sum(x, n))

Note that I also added some short docstrings to describe what each function does and simplified getting the maximum, your inner call to max was not needed. The optional keyword argument argument default of max is the default value if the iterable is empty.

I also added a if __name__ == "__main__": guard to allow importing from this script from another script without the code being run.

Here is the performance measured against your second function (the first one is way too slow) once for the input x 7 and once for 14 n:

You can see that this code is not only faster in general, it also becomes much faster if n > x / 2.


I would call this "more idiomatic" but I'm still not satisfied with it. Rust uses Iterators in a lot of ways, e.g. look at this implementation:

pub fn num_digits(num: i32) -> Vec<i32> {
    let mul = if num < 0 { -1 } else { 1 };
    num.to_string()
        .chars()
        .filter_map(|x| x.to_digit(10))
        .map(|x| (x as i32) * mul)
        .collect()
}

The mul variable is just for determining if you want negative or positive numbers.

Because i32 implements the Display trait you can call to_string on it, which will give you a String representation of the i32.
Next is just iterating of the characters of the String and trying to convert them to a digit. - will be ignored, because it is not a digit and filter_map will filter all Results, that will return a Err. The next thing is to convert the numbers to a i32 (because to_digit gives an u32) and either making them negative if the original number was negative or staying positive.

collect will put all the numbers into a collection, in this case a Vec because the type can be deduced by Rust (because of the return type)


Repeatedly fetching a URL until the response contains "state: INIT"

Inconsistent logic

In one place the script checks http://$HOSTNAME:8080/beat,
in another, it checks for a local process listening on port 8080.
This only makes sense if $HOSTNAME the name of the local machine.
It will make more sense to replace $HOSTNAME with hard-coded localhost.

Use exit code directly

Instead of this:

DATA=$(wget -O - -q -t 1 http://$HOSTNAME:8080/beat)
if [ $? -eq 0 ]
then
    break

You could use the exit code directly like this:

if DATA=$(wget -O - -q -t 1 http://$HOSTNAME:8080/beat)
then
    break

Another way:

DATA=$(wget -O - -q -t 1 http://$HOSTNAME:8080/beat) && break

Math in Bash

Instead of this:

let RETRY-=1

There are slightly simpler alternatives:

((RETRY -= 1))
((RETRY--))


On Style

“Quicksort” is customarily written as one word – the method should be called quicksort, not quick_sort. What’s more, this is an implementation detail and a public API shouldn’t reveal this (it’s subject to change), hence sort would be an even better name.
Some of your comments are redundant: “Check if the array is having one element or not” – that is (and should be!) obvious from the code. Don’t comment here. Reserve comments to explain why you do something. The next comment (“choose a pivot”) is better since that’s not immediately obvious from the code. However, it would be better to make it obvious in code and maybe have a comment describe how you choose the pivot (e.g. simple median).

The other comments are redundant again.
Furthermore, indenting the comments to the correct level would increase readability. As it stands, the comments visually hack the code into pieces.
Names: l_list and g_list contain unnecessary information that would easily be inferred from context – list, and their actual function is codified in just one letter. Rename them to lesser and greater or similar.

temp_list as a parameter is actually wrong: it’s not really temporary, it’s just the input. And again, list is a bit redundant. In fact, a one-letter identifier is acceptable here (but that’s the exception!). How about a for “array”?

Code

Use the idiomatic [] instead of list() to initialise lists.
The first elif is unnecessary, and causes the subsequent code to be indented too much. Remove it. (Also, it should logically be an else, not an elif).
Your choice of the pivot is a bit weird. Why two cases? Why not just use the middle? pivot = a[len(a) // 2]
Your code discards duplicate elements: quick_sort([1, 2, 3, 2]) will yield [1, 2, 3].
blufox has already remarked that your merge routine is more convoluted than necessary. In fact, you could just use concatenation here, lesser + [pivot] + greater (but this again discards duplicates)
It’s also a good idea to explicitly comment invariants in such algorithmic code.

Putting It Together

import itertools

def sort(a):
    def swap(i, j):
        tmp = a[i]
        a[i] = a[j]
        a[j] = tmp

    if len(a) < 2:
        return a

    lesser = []
    greater = []
    # Swap pivot to front so we can safely ignore it afterwards.
    swap(0, len(a) // 2)
    pivot = a[0]

    # Invariant: lesser < pivot <= greater
    for x in itertools.islice(a, 1, None):
        if x < pivot:
            lesser.append(x)
        else:
            greater.append(x)

    return sort(lesser) + [pivot] + sort(greater)

Bonus: Algorithmic Considerations

As blufox noted, this implementation requires more additional memory than necessary.  This is acceptable when working with immutable data structures, but becomes quite expensive when used with mutable arrays.

A normal, mutable quicksort implementation consists of two steps:

in-place partitioning along a pivot
recursive sorting of the two partitions

The second step is trivial; the partitioning and choice of pivot however require some sophistication, otherwise they will have degenerate worst cases (even without considering the worst-case input “sorted array”). The definitive paper in this regard is Engineering a sort function by Bentley and McIlroy. It is one of the clearest, most thorough computer science papers ever written and I heartily recommend its reading.

That said, no “toy” implementation will ever replace an industry-strength implementation and attempting to do so is largely a waste of time, so it’s entirely reasonable to deliberately simplify an implementation by ignoring some performance considerations.

In this regard the implementation above fares quite well. Just for the gained understanding I would still suggest that you attempt writing a variant which uses an in-place partitioning step.


Showing an image based on the battery level

I think this code is easier to read and should result in significantly less comparisons, as it just compares in every step the lower bound, where as your define macro checks twice each. And note that you are checking also equality. this should result into

at least 2 checks at cpu level and
checking equality for floats in nver a good idea, as due to rounding errors they tend to be not equal, even if in pure math they should be (a 1 might be save as 0.99 or 1.001)
and if you would check integer numbers for being in some range it make sense, to have an equal check just on one bound  like if (a <= higherNum && b > lowerNum)

my code suggestion

-(NSUInteger)batteryLevel
{
    UIDevice *device = [UIDevice currentDevice];
    float level = device.batteryLevel;
    if(level > .99) return 100;
    if(level > .80) return 90;
    if(level > .64) return 75;
    if(level > .40) return 50;
    if(level > .34) return 30;
    if(level > .14) return 20;
    return 10;
}

-(UIImage *)imageForBatteryLevel
{
    NSUInteger level = [self batteryLevel];
    NSString *imageName;
    if(level > 99){
        imageName = @"battery100fullycharged.png";
    } else {
        imageName = [NSString stringWithFormat:@"battery%d.png", level];
    }
    return [UIImage imageNamed:imageName];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (KEY_PATH_IF_THEN(@"batteryLevel")) {
        LabelBatteryStatus.text = [NSString stringWithFormat:@"%.0f%%", device.batteryLevel * 100];
        batteryImage.image = [self imageForBatteryLevel];
    }
}

I was taught at university, that in assembler code checking equality is actually done by checking, that the value is neither smaller nor greater, this makes it 2 comparisons. I am not sure, that this is true for every CPU, but let's walk through an example with that.

Let's assume, the level is down to 2%. with your code, it will go liek this:

is .02 * 100 bigger or equal than 100     and
is .02 * 100 smaller or equal than 100    -> No
is .02 * 100 smaller or equal than 99     and
is .02 * 100 bigger or equal than 81 -> No
is .02 * 100 smaller  or equal than 80 and
is .02 * 100 bigger or equal than 65 -> No
is .02 * 100 smaller  or equal than 64 and
is .02 * 100 bigger or equal than 41 -> No
is .02 * 100 smaller  or equal than 40 and
is .02 * 100 bigger or equal than 35 -> No
is .02 * 100 smaller  or equal than 34 and
is .02 * 100 bigger or equal than 15 -> No
is .02 * 100 smaller  or equal than 14 -> Yes

As you see you have 13 comparisons for smaller or bigger and 13 for equal. that yields in 39 comparisons. Additionally you have 13 times the same floating number multiplication (.02 * 100). And a gap between the boundaries: If the percentage would result in 14.5, no rule would be triggered.

Let's use my rules

is .02 > .99 -> No
is .02 > .80 -> No
is .02 > .64 -> No
is .02 > .40 -> No
is .02 > .34 -> No
is .02 > .14 -> No

=> return 10

As you see, I have maximum 6 comparisons and no floating point multiplication.


You could consider creating a class that holds the indices for a larger amount of text (for example a paragraph or a section or a subsection in the text). That class would have the absolute index for where in the file it begins and relative indices within the paragraph/section each line begins.

Whenever a new line is added or removed only the lines within that paragraph/section would have to be updated and the absolute start index of all the following sections as well.

(I don't know what text you write or what you use the line starts for).

You could still find a specific line very easily (and probably very fast) by enumerating the absolute indices of the paragraphs/sections and when you find the right section enumerate it's lines.


Loading interstitial adMob in different threads

There is no need to use Thread class you can directly do this:

// loading ads
    handler = new Handler();

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadInterstitialAd();
                }
            }, 5000);

So what is happening your handler will schedule your Runnable after 5 sec, you don't have to instanciate Thread and call runnable again.


Bugs

There is no call to va_end()

 The va_start() macro must be called first, and it initializes ap, which can be passed to va_arg() for each argument to be processed.  Calling
 va_end() signals that there are no further arguments, and causes ap to be invalidated.  Note **that each call to va_start() must be matched by a
 call to va_end(), from within the same function**.

Char and Int do not have the same size.

This advice was wrong:

    case 'c':
        cTemp = va_arg(lList, int);

I am surprised this passes your unit tests. It will read a value off the parameter list but also advance it sizeof(int) places. While a character is only of length sizeof(char).

Note  sizeof(int) > sizeof(char)
      sizeof(char) == 1

I am going to leave the above in (because it is a learning experience for me).

From:  @PeteBecker C99 Section:  6.5.2.2/7

  If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type. The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.

Thus the char argument is promoted to int when effectively pushed to the stack. So you need to use int when reading it from the var args list. Thus the code is correct.

Unchecked increment:

 default:
          break;
       }
       pcFmt++;

Pretty sure this would break if I used the string "%"

Notes:

Whenever you call PRINTCHAR() you also execute nChars++; so why not put both into the same functioin.

Extensions you should add in the long run.

You cover the bare minimum

You have format d/s/c but in printf there are a lot more with a lot more options: nore Types, type Extension (long/short), width, more formatting, etc.

No Locale Coverage

Output printing is affected a lot by current locale.


Count number of occurrences of each word of text, display as circles of varying size

Needless work to get in sorted order.

I'd like to take a look at the following section:

words = Counter(re.findall(r"[\w']+", text.lower())).most_common() # Split words

while words: # While the list of words isn't empty,
    max_occ = max(words, key=itemgetter(1))[1] # Take current max occurrence of the list

    for word in words:

        if word[1] == max_occ: # If the current word's occurrence is same as the max occurrence
            curr_word = word

            if len(circle.radius) != 1:
                c = circle.Circle(circle.radius[-1], word[0]) # Draw a circle with the current largest size of circle.radius
                c.display() # Displaying the word on the circle
                circle.radius.pop() # Remove that current largest size
            else:
                c = circle.Circle(30, word[0]) # When there's only one size left (the smallest one), make all other words that size.
                c.display()

            words = [x for x in words if x != curr_word] # Change the list so that the words already dealt with are gone, making a new max_occ

First, let's look at the help of most_common:

most_common(self, n=None) unbound collections.Counter method
    List the n most common elements and their counts from the most
    common to the least.  If n is None, then list all element counts.

So, they are in exactly the order you want. Thus, we can replace some code

words = Counter(re.findall(r"[\w']+", text.lower())).most_common()
for word in words:
    if len(circle.radius) != 1:
        c = circle.Circle(circle.radius[-1], word[0]) # Draw a circle with the current largest size of circle.radius
        c.display() # Displaying the word on the circle
        circle.radius.pop() # Remove that current largest size
    else:
        c = circle.Circle(30, word[0]) # When there's only one size left (the smallest one), make all other words that size.
        c.display()

Notice how the while and if are now both gone? All because of how .most_common already guarantees they are ordered by max-occurence.

Code duplication in getting the radius

Let's take a look at the inner if:

if len(circle.radius) != 1:
    c = circle.Circle(circle.radius[-1], word[0]) # Draw a circle with the current largest size of circle.radius
    c.display() # Displaying the word on the circle
    circle.radius.pop() # Remove that current largest size
else:
    c = circle.Circle(30, word[0]) # When there's only one size left (the smallest one), make all other words that size.
    c.display()

I'm going to do something sneaky: I see how the circle.radius.pop() and c.display() are unrelated, and that we can swap them.

if len(circle.radius) != 1:
    c = circle.Circle(circle.radius[-1], word[0]) # Draw a circle with the current largest size of circle.radius
    circle.radius.pop() # Remove that current largest size
    c.display() # Displaying the word on the circle
else:
    c = circle.Circle(30, word[0]) # When there's only one size left (the smallest one), make all other words that size.
    c.display()

Now, I see how both the branches of the if end with the same: the c.display() (and a comment which I'll ignore ;) ).

if len(circle.radius) != 1:
    c = circle.Circle(circle.radius[-1], word[0]) # Draw a circle with the current largest size of circle.radius
    circle.radius.pop() # Remove that current largest size
else:
    c = circle.Circle(30, word[0]) # When there's only one size left (the smallest one), make all other words that size.
c.display()

Another thing I'd like to note. circle.radius.pop() actually returns a value. What value? The last value in the list, that is circle.radius[-1]. Let's inline it.

if len(circle.radius) != 1:
    c = circle.Circle(circle.radius.pop(), word[0]) # Draw a circle with the current largest size of circle.radius
else:
    c = circle.Circle(30, word[0]) # When there's only one size left (the smallest one), make all other words that size.
c.display()

Ooh, see how they now have almost the same body? All that differs is the calculation of the radius. Let's move getting the radius outside of the construction of the circle.

if len(circle.radius) != 1:
    radius = circe.radius.pop()
    c = circle.Circle(radius, word[0]) # Draw a circle with the current largest size of circle.radius
else:
    radius = 30
    c = circle.Circle(radius, word[0]) # When there's only one size left (the smallest one), make all other words that size.
c.display()

and now we do the same trick as before: moving shared code outside of a branch

if len(circle.radius) != 1:
    radius = circe.radius.pop()
else:
    radius = 30
c = circle.Circle(radius, word[0])
c.display()

Combining above results

words = Counter(re.findall(r"[\w']+", text.lower())).most_common()
for word in words:
    if len(circle.radius) != 1:
        radius = circle.radius.pop()
    else:
        radius = 30
    c = circle.Circle(radius, word[0])
    c.display()


Converting a 1D Array of Strings to a 2D Array in Python

A few issues:

Probably better to follow pep8
This isn't a method, it is a function
When doing 2D numpy indexes, you can do twoDArray[x, y]
You don't really need a numpy array, a list of lists works just as well.  Or better yet just just translate the 2D index into a linear index mathematically.  This also avoids the substantial overhead of converting the list to a numpy array.  You could even use np.ravel_multi_index to do the 2D to 1D conversion for you.


There are a few things how this could be improved.

First, a few minor quibbles about syntax:

When using a type annotation, do not put a space before the : – name: Type, please. (source)
In a chain of higher-order methods, do not use the . to invoke the method. For example this

val tentative = edges.flatMap(e => Set(e.from, e.to)).map(n => (n, if (n.value == start)  Some(List.empty[Edge[T]]) else None )).toMap

should be

val tentative = edges flatMap (e => Set(e.from, e.to)) map (n => (n, if (n.value == start) Some(List.empty[Edge[T]]) else None)).toMap

(source)
When a chain of transformations is very long, splitting inside the lambdas can be an acceptable solution:

val tentative = edges flatMap (
    e => Set(e.from, e.to)
  ) map (n =>
    (n, if (n.value == start) Some(List.empty[Edge[T]]) else None)
  ).toMap

yield { block } is “evil” and should be avoided. for-comprehensions can be rewritten less clearly with flatMap and filter, but this may actually be preferable when the transformations are deeply nested.

Now let's look at this piece of your code:

for(edge <- fromHere if tentative.contains(edge.to)) yield {
  tentative.get(edge.to) match {
    case None => throw new Error("broken algorithm")
    case Some(Some(knownroute)) if (knownroute.map(_.dist).sum < route.map(_.dist).sum + edge.dist) => (edge.to, Some(knownroute))
    case _ =>(edge.to, Some(edge :: route))
  }
}

As I said, this could be rewritten to avoid the comprehension.

fromHere filter (edge => tentative.contains(edge.to)) flatMap { edge =>
  tentative.get(edge.to) match {
    case None => throw new Error("broken algorithm")
    case Some(Some(knownroute)) if (knownroute.map(_.dist).sum < route.map(_.dist).sum + edge.dist) => (edge.to, Some(knownroute))
    case _ => (edge.to, Some(edge :: route))
  }
}

The tentative.get(…) returns an Option, which will be None if no element for that key was found. But that means we can get rid of the filter! Instead, we map over the result of the get, which removes one level of Options:

fromHere flatMap { edge =>
  tentative.get(edge.to) map {
    case Some(knownroute) if (knownroute.map(_.dist).sum < route.map(_.dist).sum + edge.dist) => (edge.to, Some(knownroute))
    case _ => (edge.to, Some(edge :: route))
  }
}

Destructuring the Option with Pattern matching is a bit tedious. Actually, we want to do one thing, orElse some default case.

fromHere flatMap { edge =>
  tentative.get(edge.to) map { maybeRoute =>
    maybeRoute filter (knownroute =>
      knownroute.map(_.dist).sum < route.map(_.dist).sum + edge.dist
    ) map (knownroute =>
      Pair(edge.to, Some(knownroute)
    ) getOrElse (Pair(edge.to, Some(edge :: route)))
  }
}

But this is an unreadable mess! Yes, it somehow is. We can improve this by adding a Route class, e.g:

case class Route[T](route: List[Edge[T]], dist: Int) {
  val length = route.length

  def this(route: List[Edge[T]]) = this(route, route map (_.dist) sum)

  def this() = this(List.empty[Edge[T]], 0)

  def ::(edge: Edge[T]) = Route(edge :: route, dist + edge.dist)
}

val tentative: Map[Node[T], Option[Route[T]] = ...

The main advantage is that this keeps track of a route's distance, which means the above code becomes the slightly more accessible

fromHere flatMap { edge =>
  tentative.get(edge.to) map { maybeRoute =>
    val maybeBetterRoute =
      maybeRoute filter (knownRoute => knownRoute.dist < route.dist + edge.dist)
    maybeBetterRoute map (knownRoute =>
      Pair(edge.to, Some(knownroute)
    ) getOrElse (
      Pair(edge.to, Some(edge :: route))
    )
  }
}

You calculate the fromHere each time, which is an O(n) calculation, I think:

val fromHere = edges.filter(e => e.from == node)

It may be better to build a Map[Node[T], List[Edge[T]]] before the recursion, which is also a fairly cheap operation:

val edgesBySource = edges groupBy (_.from)

then: val fromHere = edgesBySource.get(node).flatten. I assume this would pay off soon for non-tiny graphs.


Seconds between datestimes excluding weekends and evenings

1. Issues

Your code fails in the following corner cases:

a and b on the same day, for example:

>>> a = datetime(2012, 11, 22, 8)
>>> a.weekday()
3          # Thursday
>>> seconds_between(a, a + timedelta(seconds = 100))
54100.0    # Expected 100

a or b at the weekend, for example:

>>> a = datetime(2012, 11, 17, 8)
>>> a.weekday()
5          # Saturday
>>> seconds_between(a, a + timedelta(seconds = 100))
21700.0    # Expected 0

a after STOP_HOUR or b before START_HOUR, for example:

>>> a = datetime(2012, 11, 19, 23)
>>> a.weekday()
0          # Monday
>>> seconds_between(a, a + timedelta(hours = 2))
28800.0    # Expected 0

Also, you count the weekdays by looping over all the days between the start and end of the interval. That means that the computation time is proportional to the size of the interval:

>>> from timeit import timeit
>>> a = datetime(1, 1, 1)
>>> timeit(lambda:seconds_between(a, a + timedelta(days=999999)), number=1)
1.7254137992858887

For comparison, in this extreme case the revised code below is about 100,000 times faster:

>>> timeit(lambda:office_time_between(a, a + timedelta(days=999999)), number=100000)
1.6366889476776123

The break even point is about 4 days:

>>> timeit(lambda:seconds_between(a, a + timedelta(days=4)), number=100000)
1.5806620121002197
>>> timeit(lambda:office_time_between(a, a + timedelta(days=4)), number=100000)
1.5950188636779785

2. Improvements

barracel's answer has two very good ideas, which I adopted:

compute the sum in seconds rather than days;
add up whole days and subtract part days if necessary.

and I made the following additional improvements:

handle corner cases correctly;
run in constant time regardless of how far apart a and b are;
compute the sum as a timedelta object rather than an integer;
move common code out into functions for clarity;
docstrings!

3. Revised code

from datetime import datetime, timedelta

def clamp(t, start, end):
    "Return `t` clamped to the range [`start`, `end`]."
    return max(start, min(end, t))

def day_part(t):
    "Return timedelta between midnight and `t`."
    return t - t.replace(hour = 0, minute = 0, second = 0)

def office_time_between(a, b, start = timedelta(hours = 8),
                        stop = timedelta(hours = 17)):
    """
    Return the total office time between `a` and `b` as a timedelta
    object. Office time consists of weekdays from `start` to `stop`
    (default: 08:00 to 17:00).
    """
    zero = timedelta(0)
    assert(zero <= start <= stop <= timedelta(1))
    office_day = stop - start
    days = (b - a).days + 1
    weeks = days // 7
    extra = (max(0, 5 - a.weekday()) + min(5, 1 + b.weekday())) % 5
    weekdays = weeks * 5 + extra
    total = office_day * weekdays
    if a.weekday() < 5:
        total -= clamp(day_part(a) - start, zero, office_day)
    if b.weekday() < 5:
        total -= clamp(stop - day_part(b), zero, office_day)
    return total


a as alias for products is not the best choice.
You don't use anything from products in your subqueries. So you don't need to join it.
If you only need the productID, you can also skip the products table in the outer query and use oa.productid instead.
You don't need a rowId - You can use the SUM to order the result.

So you query could look like:

SELECT p.ID, collection.value as title, colour.value as colour, type.value as type
FROM orderrows oa
JOIN order o ON o.ID = oa.orderID
JOIN products p ON oa.productid = p.ID
JOIN productparameter as collection ON collection.productid = p.ID AND collection.parameterid = 'collection_id'
JOIN productparameter as type ON type.productid = p.ID AND type.parameterid = 'type_id'
JOIN productparameter as colour ON colour.productid = p.ID AND colour.parameterid = 'colour_id'
JOIN
(
    SELECT collection.value, SUM(oa.productprice * oa.productamount) as total
    FROM orderrows oa
    JOIN order o ON o.ID = oa.orderID
    JOIN productparameter as collection ON collection.productid = oa.productid AND collection.parameterid = 'collection_id'
    WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
    GROUP BY collection.value
) as collection_sort ON collection.value = collection_sort.value
JOIN
(
    SELECT colour.value, SUM(oa.productprice * oa.productamount) as total
    FROM orderrows oa
    JOIN order o ON o.ID = oa.orderID
    JOIN productparameter as colour ON colour.productid = oa.productid AND colour.parameterid = 'colour_id'
    WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
    GROUP BY colour.value
) as colour_sort ON colour.value = colour_sort.value
JOIN
(
    SELECT type.value, SUM(oa.productprice * oa.productamount) as total
    FROM orderrows oa
    JOIN order o ON o.ID = oa.orderID
    JOIN productparameter as type ON type.productid = oa.productid AND type.parameterid = 'type_id'
    WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
    GROUP BY type.value
) as type_sort ON type.value = type_sort.value
WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
GROUP BY a.ID
ORDER BY collection_sort.total DESC, colour_sort.total DESC, type_sort.total DESC

That are 37 lines of code instead of 64.

But there are still three subqueries which are almost equal. You can merge them to this one:

SELECT pp.parameterid, pp.value, SUM(oa.productprice * oa.productamount) as total
FROM orderrows oa
JOIN `order` o ON o.ID = oa.orderID
JOIN productparameter as pp ON pp.productid = oa.productid
WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
  AND collection.parameterid IN ('collection_id', 'colour_id', 'type_id')
GROUP BY pp.parameterid, pp.value

and use conditional aggregation to pivot the result in the outer query:

SELECT
    p.ID,
    MAX(CASE WHEN t.parameterid = 'collection_id' THEN t.value END) as collection,
    MAX(CASE WHEN t.parameterid = 'colour_id'     THEN t.value END) as colour,
    MAX(CASE WHEN t.parameterid = 'type_id'       THEN t.value END) as `type`
FROM (
    SELECT pp.parameterid, pp.value, SUM(oa.productprice * oa.productamount) as total
    FROM orderrows oa
    JOIN `order` o ON o.ID = oa.orderID
    JOIN productparameter as pp ON pp.productid = oa.productid
    WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
      AND collection.parameterid IN ('collection_id', 'colour_id', 'type_id')
    GROUP BY pp.parameterid, pp.value
) t
JOIN productparameter pp ON pp.parameterid = t.parameterid
JOIN products p ON p.ID = pp.productid
JOIN orderrows oa ON oa.productid = p.ID
JOIN `order` o ON o.ID = oa.orderID
WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
GROUP BY p.ID
ORDER BY
    MAX(CASE WHEN t.parameterid = 'collection_id' THEN t.total END) DESC,
    MAX(CASE WHEN t.parameterid = 'colour_id'     THEN t.total END) DESC,
    MAX(CASE WHEN t.parameterid = 'type_id'       THEN t.total END) DESC

(24 lines)


It looks like based on the 2 inner loops where you are calculating maxMag you could refactor the code to utilize Parallel.ForEach() so you can start to use multiple cores for the math.  Just put all of the individual maxMags into a concurrent dictionary.  When your done, run your aggregation methods.  You'll have to decide whether it is better as an array that gets copied, or whether to refactor them into a concurrent collection type.  I hope this helps.

Edit/Update:

Per your comment relating to using all cores "However, the best improvement this would bring on typical hardware would be 8x. 8x isn't quite going to be enough for my application." (found under cgilmeanu's answer)

If utilizing all of the computer resources and taking an 8-fold gain won't get anywhere close, then ...

Answer = you need to horizontally scale across multiple computers until you reach the point where you are satisfied with the "timed" outcome.

Going to c, c++, or .net-under-the-hood should help make gains for you.  However, commonly, the programming involved results in something complicated, hard to understand, and more extensive documentation.  This can make it tough to be nimble and make changes.  Also, if you can assume that the computational load/iterations may increase in the future, your extensive efforts in extremely fine tuning this item may be all for nothing since it was internally just vertical scaling by optimization.


I don't see how that <xsl:otherwise> would ever do anything based on your sample xml. The template matches on appendix/title so your context would be the title element. Applying templates to appendix children of title would be a no-op. I think something like this would be closer to what you want

<xsl:template match="appendix[title = 'Answer Key']">
  <div class="answer-key">
    <xsl:call-template name="solutions"/>
  </div>
</xsl:template>

<xsl:template match="appendix">
  <!-- Do something standard -->
</xsl:template>

Here, the first template has a higher implicit priority than the second template so it will match on the "Answer Keys". If the predicate evaluates to false, the second template will then match. Note though the code above will behave differently if the called template "solutions" depends on having a title element context node as it would in your code sample. In this sample the context would be the appendix element, which seems like possibly a more appropriate point in the document hierarchy to be performing whatever operations you intend to do.


Pascal's triangle for an interview in PHP

In regards to the comments: Yes, this is a good place for this so long as it works as is and you are asking about the code and not the algorithm. If you are asking about the algorithm this should have stayed on programmers.SE. If you are asking if this will work, then you should test it first, then if you can't find a solution you should post this to SO. Now, assuming this works and you're not asking about the algorithm, here are my thoughts:

A number of these points may be nitpicking, but the interviewers are likely to nitpick as well since they have so little code to review to determine how good you are. First example of this are your variable and function names, which could stand to be a bit more descriptive. I can guess what "r" might be, but spelling it out wouldn't hurt, especially if that variable might get lost in layers of code. It makes your code "self-documenting", this means less actual documentation and easier future integration.

Unless you have to add a number of elements on to an array at the same time, don't use array_push(). There is no need to call a function to do something that can be done without one. This is also explicitly explained on the PHP documentation for this function should you need further proof.

$local[] = 1;//good

array_push( $local,
    1,
    2,
    //etc...
);//also good

array_push( $local, 1 );//bad

Watch your indentation. That for loop is needlessly indented. Needless whitespace and indentation add "weight" to your documents. Not much at any one time, but a weight that can build up steadily, especially if you are of the faction that uses spaces instead of tabs. This isn't ever likely to cause any real world difficulties, except maybe slightly larger file sizes, but again, I'm nitpicking.

Something else you are going to get tagged on is all of these magic numbers. Where are these 1's and 2's coming from? If those numbers mean something, then you should create constants or variables to define it. Constants if immutable, variables if mutable. If, as in your first return statement you are merely returning the value of $r, as it appears, then you can just typecast it.

if( $r == 1 ) {
    return array( ( array ) $r );
}

Instead of doing the same operation, $r - 2, over and over again, set the value to a variable and use that instead. Its overhead may be slight, and again a nitpick, but it still adds up if done enough. Besides, it makes for much more legible code.

$r2 = $r - 2;//horrible name, don't use this
for( $i = 0; $i < $r2 && $r > 2; $i++ ) {

This next suggestion is similar to one I've already given. Watch your indentation. You have an if/else statement when you could really get away with just an if statement. Since it has an early return, you can drop the else statement, this removes one layer of indentation across six lines of code. In larger systems this could easily add up to quite a bit more and is easily one of the easiest, most visual, refactoring you can do.

The last bit of advice would be to use var_dump() over print_r(). While this may be a matter of preference, I find the type output beneficial, especially in cases where you could somehow get an empty array or FALSE value.

EDIT

Interesting coincidence here, but I'm taking a course on Coursera (Functional Programming in Scala), and one of the things we were required to do was find the value of a given coordinate on a pascal triangle. This assignment reminded me of this post so I thought I'd revisit it, but I wanted to wait until the deadline had been reached before posting this. Below is the code I used to functionally find the value.

Note: I'm using spoilers to give you a chance to work it out. Try and do these yourself before peeking.

      function pascal( $col, $row ) {
        if( $col == 0 || $col == $row ) {
            return 1;
        } else if( $col == 1 || $col == $row ) {
            return $row;
        } else {
            return pascal( $col, $row - 1 ) + pascal( $col - 1, $row - 1 );
        }
    }

Note: I stressed functional, but there are other ways of doing this. I'm merely keeping with my assignment's guidelines.
Note: I know I'm violating some of my own advice. The instructions I was given in my assignment stressed not to use variables, so I'm not.

So, given we can now find a value at any given coordinate, we should easily be able to use this to print a pascal triangle too. All we need is to determine how big we want our triangle to be and we can loop for it. I'm going to use 10, but you can change that amount to any value you want and it will still work. Again, no peeking!

      for( $i = 0; $i < 10; $i++ ) {
        for( $j = 0; $j <= $i; $j++ ) {
            echo pascal( $j, $i ) . ' ';
        }
        echo '<br />';
    }

There you have it. Not only have you printed a pascal triangle, but you've also created a function that can be reused to serve a better purpose, namely finding a coordinate value.


Generating all subarrays from an array of Integer

To answer your immediate question: Yes, it is fine to mutate an array while enumerating its elements. The reason is that

for res in result { ... }

is equivalent to

var iter = result.makeIterator()
while let res = iter.next() {
    // ...
}

and that arrays are value types in Swift: Mutating result inside the loop creates a new value and does not affect the original array that the iterator is using. See Remove element from collection during iteration with forEach on Stack Overflow for more details.

There are some possible simplifications. Here

var resi = res
resi.append(arr[i])
result.append(resi)

is is not necessary to declare another array variable, this can be shortened to

result.append(res + [arr[i]])

A better name for the res variable might be subarray or subset.

Instead of looping over the array indices

for i in 0..<arr.count {
    // ... do something with `arr[i]` ...
}

you can enumerate the array (as you already do in the inner loop)

for elem in arr {
    // ... do something with `elem` ...
}

The

guard arr.count >= 1 else { return [arr] }

is not needed. Your algorithm already does “the right thing” for an empty array.

So this is what we have so far:

func subarrays(_ arr: [Int]) -> [[Int]] {
    var result = [[Int]]()
    for elem in arr {
        for subarray in result {
            result.append(subarray + [elem])
        }
        result.append([elem])
    }
    result.append([])
    return result
}

It becomes a bit simpler if result is not initialized with an empty list, but with a list containing the empty subset. Adding the array element itself, and the empty set at the end of the function is no longer necessary:

func subarrays(_ arr: [Int]) -> [[Int]] {
    var result: [[Int]] = [[]]
    for elem in arr {
        for subarray in result {
            result.append(subarray + [elem])
        }
    }
    return result
}

(The subset are returned in a different order now, though.)

The inner loop could be replaced by a map  operation:

func subarrays(_ arr: [Int]) -> [[Int]] {
    var result: [[Int]] = [[]]
    for elem in arr {
        result.append(contentsOf: result.map { $0 + [elem] })
    }
    return result
}

or even the entire function body replaced by a single expression:

func subarrays(_ arr: [Int]) -> [[Int]] {
    return arr.reduce(into: [[]], { (result, elem) in
        result.append(contentsOf: result.map { $0 + [elem] })
    })
}

but that is a matter of taste – is not necessarily easier to read.

There is nothing particular with respect to integers in the algorithm, the function can be made generic to take arrays of any element type – or even arbitrary sequences.

Finally I would call it subsets(of:), which is what the function computes:

func subsets<S: Sequence>(of seq: S) -> [[S.Element]] {
    var result: [[S.Element]] = [[]]
    for elem in seq {
        for subset in result {
            result.append(subset + [elem])
        }
    }
    return result
}


Enum string parse and get custom attribute assign to array

Overall code seems OK then I highlight just few minor issues (and I propose a slightly bigger change to simplify code).

1.

public AuthorizeRoles(params object[] arrayParam)

arrayParam is not a descriptive name, what is it? List of roles? Make it clear changing name to - for example - roles.

2.

arrayParam.Select(myField => Enum.Parse(typeof(MyEnum), myField.ToString()))

You're converting each arrayParam item to a string however you're not doing any check, if one of them is null then code will fail with NullReferenceException for a long line packed with a lot of code. Not so helpful. You may check in advance with:

if (arrayParam.Any(x => x == null))
    throw new ArgumentException("...");

Otherwise just let Enum.Parse() fail and use Convert.ToString(myField) won't throw for null input. Note that if type is restricted to be string or MyEnum then you may change your function definition accordingly:

public AuthorizeRoles(params string[] arrayParam)
public AuthorizeRoles(params MyEnum[] arrayParam)

Note that a weird user may have this:

object[] pars = null; // It may be a function argument...
AuthorizeRoles(pars);

Then you should also check if arrayParam is null itself:

if (arrayParam == null)
    throw new ArgumentNullException("arrayParam");

3.

.Select(field => GetCustomAttribute(field, typeof(DescriptionAttribute))))
.OfType<DescriptionAttribute>()

In this case you do not need OfType<DescriptionAttribute>() because values are just of one type, it's a minor optimization but I think it's better to don't confuse future readers and Cast<DescriptionAttribute>() or directly (DescriptionAttribute) before GetCustomAttribute().

Now if it's allowed to change little bit your code I think it may be simplified. Pick this part:

arrayParam.Select(myField => Enum.Parse(typeof(MyEnum), myField.ToString()))
    .Select(temp => temp.GetType().GetField(temp.ToString()))

First you convert input values to strings then you parse them to have MyEnum and finally you convert them back to string to use them with GetField(). One step should be omitted:

arrayParam.Select(x => Convert.ToString(x))
    .Select(x => typeof(MyEnum).GetField(x))

GetCustomAttribute() is a custom helper function, if you change it to this prototype:

private static T GetCustomAttribute<T>(FieldInfo field)
    where T : Attribute

Then last few lines of your code may be simplified (cast is not required and last .Select() may be merged in previous one). Note that with the generic argument T we don't even need a Type parameter (you can obtain type using typeof(T)).

Then if we rewrite whole function for an overview we have something like this:

public AuthorizeRoles(params object[] roles)
{
    if (roles == null)
        throw new ArgumentNullException("roles");

    if (roles.Any(x => x == null))
        throw new ArgumentException("...");

    allowed = roles.Select(x => Convert.ToString(x))
        .Select(x => typeof(MyEnum).GetField(x))
        .Select(x => GetCustomAttribute<DescriptionAttribute>(x).Description)
        .ToArray();
}

The two .Select() may be merged but I'd not scarify readability just to keep code shorter and a minor performance gain (after all we're working with Reflection here...) You may also want to add some checks before the second .Select() or inside GetCustomAttribute<T>() to throw a meaningful error message if one of given values is not a valid enum element.


Python: Speeding up vector and matrix operations

What you compute with the presented code is

matrix_j = array([ J[j,k]**2 for k in range(N) ])

(where N=800 is the vector length) so that

d[i] = sum( (J[j,k]**2 - I[i,k]**2)**2 for k in range(N) )

This does not make much sense geometrically.

What you could have intended, by what might be implied by the formulas and variable names, is to have J[j] and I[i] as actual row vectors which can be achieved by transforming the tables I,J into matrices,

I,J = np.matrix(I), np.matrix(J)

so that then d[i] is the square of the Frobenius norm of J[j].T*J[j]-I[i].T*I[i], which is also the sum over the squares over all matrix elements. As this matrix is symmetric, this quantity can be computed as

d[i] = np.sum(np.diag( (J[j].T*J[j]-I[i].T*I[i])**2 ))

which has the form for row vectors \$a,b\$ of equal dimension
\begin{align}\|a^Ta-b^Tb\|_F^2 &= \text{trace}((a^Ta-b^Tb)^2)\\ &=\text{trace}((a^Ta-b^Tb)(a^Ta-b^Tb))\\ &=\text{trace}(a^Taa^Ta-a^Tab^Tb-b^Tba^Ta+b^Tbb^Tb))\\ &=(aa^T)^2-2(ab^T)^2+(bb^T)^2\\ &=\|a\|^4-2\langle a,b\rangle ^2+\|b\|^4 \end{align}

Re-expressed in the rows of the original matrices, that should be 2D-arrays, not converted to matrix objects, this is

d[i] = np.dot(I[i],I[i])**2 - 2*np.dot(I[i],J[j])**2 + np.dot(J[j],J[j])**2

For a component-wise derivation see the answer of Gareth Rees.

These norm squares and scalar products should be faster to compute than the original formula. Also, pre-computing the norm squares np.dot(I[i],I[i]) allows re-use so that all len(I)+len(J) norm squares are only computed once and the main computational cost is from the len(I)*len(J) scalar products.

scipy.linalg.norm might be faster in computing the norm, as squaring can be faster than multiplying the same number to itself, but I'm not sure how that translates over the several layers of interpretation and data encapsulation.

The scalar products are elements of a matrix product of I and J.T, so that a compact computation proceeds by (all are np.array objects)

dotIJ = np.dot(I,J.T);
normI2 = [ np.dot(row,row) for row in I ];
normJ2 = [ np.dot(row,row) for row in J ];
d = np.zeros((len(I),1));
for j in range(len(J)):
    d[:,0] = [ normI2[i]**2 + normJ2[j]**2 - 2*dotIJ[i,j]**2 for i in range(len(I)) ]
    # process values of d


This looks like a good use for UNPIVOT. And you can use common table expressions to avoid repeating yourself. Like this:

WITH DIAGS AS
(
    SELECT DISTINCT VisitID as ID, Diags
    FROM
    (
        SELECT *
        FROM [AGH00]...[20110128 - AGH00#TXT]
    ) p
    UNPIVOT
    (
        Diags FOR DX IN
        (
            DX01, DX11, DX21, DX31
            , DX02, DX12, DX22, DX32
            , DX03, DX13, DX23, DX33
            , DX04, DX14, DX24, DX34
            , DX05, DX15, DX25, DX35
            , DX06, DX16, DX26, DX36
            , DX07, DX17, DX27, DX37
            , DX08, DX18, DX28, DX38
            , DX09, DX19, DX29, DX39
            , DX10, DX20, DX30, DX40
        )
    ) AS unpvt
),
A0 AS
(
    SELECT VisitID, DischDate, [Type], SubType
    FROM [AGH00]...[20110128 - AGH00#TXT]
),
AC AS
(
    SELECT VisitID, SUM(ChargsAmt) AS Charges
    FROM [AGH00]...[20110128 - AGH00Chg#TXT]
    GROUP BY VisitID
),
AP AS
(
    SELECT VisitID, SUM(Pmt) AS Payments
    FROM [AGH00]...[20110128 - AGH00Pmt#TXT]
    GROUP BY VisitID
)
VISITS AS
(
    SELECT SUBSTRING(A0.DischDate, 7, 4) + SUBSTRING(A0.DischDate, 1, 2) AS YYYYMM
        , A0.[Type]
        , A0.SubType
        , DIAGS.Diags
        , AC.Charges
        , AP.Payments
    FROM DIAGS
        LEFT JOIN A0 ON DIAGS.ID = A0.VisitID
        LEFT JOIN AC ON A0.VisitID = AC.VisitID
        LEFT JOIN AP ON A0.VisitID = AP.VisitID
)
SELECT YYYYMM, [Type], SubType, Diags
    , COUNT(*) AS [Count]
    , SUM(Charges) AS Charges
    , SUM(Payments) AS Payments
FROM VISITS
GROUP BY YYYYMM, [Type], SubType, Diags
ORDER BY YYYYMM, [Type], SubType, Diags


I would strongly recommend a different algorithm for processing your file. I would do it in a three-stage approach, requiring only two reads of the file:

on the first stage, we scan the file, and do a few things:

For each line, call the stream.tell() on the file stream, and remember the byte position.
identify all Second_Packet blocks, and the FN they relate to.
store the FN and the byte position from the Tell in to a dictionary.
identify all KEY_FRAME blocks, and create an object to represent it, with it's number. Store it in a list

the second stage involves processing the KEY_FRAME records, and identifying where the Second_Packet records are. From the map, order the requests to happen in byte-position order from the stream.
Here we scan the file again, in order of the Second_Packet byte positions and the KEY_FRAME instances they belong to.

seek in the file to the position of the first needed Second_Packet
strip off whatever information you need to complete the record.
update the KEY_FRAME instance of data with the required information

By performing only two scans through the file (the first is a full scan, the second is an in-order-but-random-and-selective scan) you reduce the amount of times you process the data.

In your current system, you are scanning the file many times (once and then an additional one for each KEY_FRAME record and an additional one again for each second...). The loops you have at the end are very costly:

for s in sentences:
    if any(('FrameNumber = '+f) in s for f in framelist):
        print 'first found'
        #do stuff

    if any(('FN = '+f) in s for f in framelist):
        print 'second found'
        #do stuff


Intersection of N lists, or of an N-d array

You can loop through a set, there is no need to wrap them in lists.
You can loop through splits, using for i in range(len(splits)): splits[i] is just long winded.
Just use for spilt in splits:.
When checking if a key is in a dictionary, don't compare to it's .keys(), just do 'a' in dict.
You should notice that you're forcing the dictionary to be pre-populated, alternately you could use collections.defaultdict.
After changing the code to use a defaultdict you should be able to notice that all you're doing is counting this:

(item for split in splits for item in set(split))

And so you could use collections.Counter instead.
In your final loop you use .keys() and then use uniques[x]. Instead you should use .items(), with tuple unpacking.
Finally you should aim at improving the readability, so I generate all the items on one line. And build the np array on another.

This can result in:

from collections import Counter

def overlap(splits):
    items = (item for split in splits for item in set(split))
    return np.array([k for k, v in Counter(items).items() if v == len(splits)])

However this does the same as np.intersect1d with two arrays as input. The docs also say, that if you wish to intersect more than two arrays you can use:

>>> from functools import reduce
>>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
array([3])


I would start by trying to make a separate package for making the requests, something like a presenter(MVP pattern - MVP in Android).
Because, the way you have it now, it is hard to be tested and inside of the activity you have more logic, breaking a bit the SRP principle( SRP ).

Now, all it is left to do is to connect the activity and the presenter and that you can do using a callback.
Also, as a bonus, all the stuff you need, presenter, etc, you can add to a dagger module.


Project Euler Question #2: Sum of even Fibonacci numbers under 4 million

Your current implementation, and the suggested improvements are all brute force implementations, i.e. enumerating all fibonacci numbers, and they will all run in O(n).

By using some mathematical tricks, you can turn this into an O(1) implementation. Since this is a project Euler problem, I won't spell out the answer, but here are some pointers:

When starting at F(0) = 1 (instead of starting at F(1) as in the problem description), every third number is an even fibonacci number
Because the fibonacci numbers are by definition based on the addition of the previous two numbers, the sum of all even fibonacci numbers up to n is equal to the sum of all fibonacci numbers up to n divided by two.
There are cool formula's to calculate the sum of fibonacci numbers and the index of the highest fibonacci number up to n. Refer to wolframalpha or wikipedia to find them.


You can refactor this method (and downloadLatestFileAWS, too), to take an optional completion handler parameter:

func requestDownloadLinkForAWS(completion: @escaping ((Result<URL, Error>) -> Void)? = nil) {
    ...

    do {
        ...
        downloadLatestFileAWS(dataResponse.bucketName, dataResponse.folderName, dataResponse.version, completion: completion)
    } catch let error {
        completion?(.failure(error))
    }
}

func downloadLatestFileAWS(_ bucket: String, _ folder: String, _ version, completion: @escaping ((Result<URL, Error>) -> Void)? = nil) {
    ...
    completion?(.success(url)) // the file URL of the saved file
}

Then you can test it:

func testDownload() {
    var result: String?

    let expectation = self.expectation(description: "download")
    requestDownloadLinkForAWS { result in
        if case .failure(_) = result {
            XCTFail("Download failed")
        }
        expectation.fulfill()
    }
    wait(for: [expectation], timeout: 10)
}

By the way, by adding a completion handler to the download method, it also offers you the opportunity to have the caller specify what UI updates should take place when the download is done. For example, you generally don’t want to bury those UI updates within downloadLatestFileAWS. Also, rather than just printing the error to the Xcode console, the caller can now specify what it wants to do when an error occurs.

That having been said, you might not want to actually perform network requests in unit tests. You might, instead mock the network service, or use URLProtocol to mock it behind the scenes.

But either way, you can make your methods testable by providing them with completion handler closures.


Finding vowels, digits, whitespaces and consonants

Your code contains a lot of duplication. It can be made much shorter by passing a predicate to the find method instead of an enum. When you do that, the whole enum Find will become unused. After that, you should rename the find method to count, so that the name matches what it is actually doing.

Your way of organizing the imports looks unusual and funny. But in the rare case that someone really looks at them (like in this code review) it makes more sense to sort them by topic instead of by length. But if it's your point that these lines are usually not looked at, it's fine.

I would make the code as simple as this:

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;

import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.IntPredicate;

public class FXMLDocumentController implements Initializable {

    @FXML
    TextField inputField;
    @FXML
    TextField vowelsField;
    @FXML
    TextField consField;
    @FXML
    TextField digitField;
    @FXML
    TextField spaceField;
    @FXML
    Button check;
    @FXML
    Button exit;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        exit.setOnAction(e -> System.exit(0));
    }

    @FXML
    void checkBtnHandle(ActionEvent e) {
        List<Runnable> tasks = Arrays.asList(
                () -> updateField(vowelsField, this::isVowel),
                () -> updateField(consField, c -> Character.isLetter(c) && !isVowel(c)),
                () -> updateField(digitField, Character::isDigit),
                () -> updateField(spaceField, Character::isWhitespace)
        );

        ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
        tasks.forEach(executor::submit);
        executor.shutdown();
    }

    private void updateField(TextField field, IntPredicate predicate) {
        String lowerCaseText = inputField.getText().toLowerCase();
        long count = lowerCaseText.chars().filter(predicate).count();
        Platform.runLater(() -> field.setText(String.valueOf(count)));
    }

    private boolean isVowel(int codePoint) {
        //checking for lower case because the input will only in lower case
        return codePoint == 'a'
                || codePoint == 'e'
                || codePoint == 'i'
                || codePoint == 'o'
                || codePoint == 'u';
    }
}

I moved the creation of the tasks lists into the checkBtnHandle method since I don't know at which exact instant the initialize method is called, and I wanted to avoid NullPointerExceptions.


There are three severe errors in your code:

Rule of Three/Five/Zero

This is an invaluable resource. Anytime you write a user-defined destructor, you will need to write the copy constructor and assignment. You lack the copy constructor or assignment, so the compiler will happily provide one for you, and that one will not do the right thing:

vector<int> v;        // we have an array of size zero with capacity 50
vector<int> v2 = v;   // we do not have two arrays: both vectors have
                      // the SAME pointer
// <== v2 gets destroyed, we run delete [] array
// <== v gets destroyed, we run delete [] array again! boom

In addition to the double free, you get the other issue in that the user might expect a deep copy but actually v2 is basically just a Java-style reference to v. Fixing this is an absolute must.

Resizing

This is definitely non-functional. You delete your member arr, then, separately from that, you create a locally scoped array arr that you write stuff into. At the end of resize(), the vector object will have a deleted local array!

The correct way to resize() is to allocate a new array (only have to do one!) of double the size, to copy/move from your member into the new array, and then simply change your member to point to the new array. This should be one allocation (of the doubled array) and one deletion (of the old array).

Off-by-one

The first push_back() writes into arr[1]. What goes into arr[0]?

Once you fix those, there are other issues with your code:

Limits on Types

When you construct like this:

vector(){
    size = 50;
    index = 0;
    T* arr = new T[size];
}

You are adding a restriction on T. Namely, that it must be default constructible:

struct X { X(int ) { } };
vector<X> v;

leads to:

main.cpp: In instantiation of 'vector<T>::vector() [with T = X]':
main.cpp:108:15:   required from here
main.cpp:26:28: error: no matching function for call to 'X::X()'
         T* arr = new T[size];
                            ^

The way to avoid this is to use global ::operator new to allocate memory without constructing any objects.

Naming

You have member variables named size, which is actually the capacity of the vector, and index, which is its size. Those names are confusing and should be changed to reflect their actual purpose.

Object Destruction

A vector owns its objects. When you pop or erase from a vector, it must release ownership - which will involve explicitly calling the destructor on your type. You do not currently do this.

Resizing, part 2

Resizing should only happen on insertion. You also do it on erase(). This is illogical. Why would removing an element lead to doubling in the array size?

operator[]

Where's the body?

const overloads

If I have a const vector<int>, I cannot do anything with it. That's not useful. empty() and length() (which should be spelled size()) can just be const member functions. There also need to be const overloads for begin(), end(), operator[], front(), and back().


Generate the name of a computer from its properties

I would highlight two things:

It is not really common to throw exception inside a property getter
Because the Name has only just a getter then you can consider to expose it as a method instead.

From implementation point of you, you can improve readability if you do something like this:
var nameBuilder = new StringBuilder();
nameBuilder.Append('I');

var siteWhitelist = new AssetSite[] { AssetSite.Sydney, AssetSite.Rotterdam };
if (!siteWhitelist.Contains(this.AssetSite))
    throw new ArgumentOutOfRangeException("Invalid site");

string site = this.AssetSite switch
{
    AssetSite.Sydney    => "S";
    AssetSite.Rotterdam => "R";
};

nameBuilder.Append(site);
nameBuilder.Append("PC");

string computerType = this.IsLaptop ?  "L" : "D";

nameBuilder.Append(computerType)
nameBuilder.Append(this.AssetTag);

return nameBuilder.ToString();

Of course you can further improve it, by introducing a Dictionary<AssetSite, string> where you can store the mapping between sites and letters.


Do not use double arithmetics when integer arithmetics can solve the problem as well. The function isPowerOfTwoMinus1 can be written simply as ((x + 1) & x) == 0.

Don't call isMersennePrime twice, just break from the loop.


Pandas Filtering based on the length of the same kind variables in a column

Good answer by Juho. Another option is a groupby-filter:
df.groupby('id').filter(lambda group: len(group) > 3)

#    samples id
# 1        2  b
# 2        3  c
# 3        4  b
# 4        5  b
# 5        6  b
# 6        7  c
# 7        8  c
# 8        9  c

To match your output order exactly, add a descending id sort: .sort_values('id', ascending=False)


Loading a Protein Data Bank file into a numpy matrix

Seeing that both your blocks are identical, you can be able to merge them using boolean logic.

First thing is that, in each case, you perform line.startswith('ATOM') so put that first.

Second, either you have only_CA being True and you need 'CA' at line[13:15] too, or you have only_CA being False. In other words, you keep the line if either only_CA is False or 'CA' is at line[13:15].

This lets you rewrite your for loop as:

for line in infile:
    if line.startswith('ATOM') and (not only_CA or line[13:15] == 'CA'):
        try:    # matrix fill-up
            CoordAtoms = np.vstack([CoordAtoms, [float(line[30:38]), float(line[38:46]), float(line[46:54])]]) # np.append
        except NameError:  # matrix declaration
            CoordAtoms = np.array([[line[30:38],line[38:46], line[46:54]]], float)

You can also extract out the line parsing at it is somehow repeated:

for line in infile:
    if line.startswith('ATOM') and (not only_CA or line[13:15] == 'CA'):
        data = [line[30:38], line[38:46], line[46:54]]
        try:    # matrix fill-up
            CoordAtoms = np.vstack([CoordAtoms, [float(x) for x in data]]) # np.append
        except NameError:  # matrix declaration
            CoordAtoms = np.array([data], float)

But you can also simplify the whole thing by converting your data to float before the try and feeding np.array data of the correct type:

for line in infile:
    if line.startswith('ATOM') and (not only_CA or line[13:15] == 'CA'):
        data = [float(line[begin:end]) for begin, end in ((30, 38), (38, 46), (46, 54))]
        try:    # matrix fill-up
            CoordAtoms = np.vstack([CoordAtoms, [data]]) # np.append
        except NameError:  # matrix declaration
            CoordAtoms = np.array([data])