Simple utility/convenience module - am I doing it right?

It was really hard to understand what you're code is doing, but it does have some easy spottable "problems":

is None vs. == None

PEP8 clearly states:

  Comparisons to singletons like None should always be done with is or is not, never the equality operators.

There's some further explaination here.

So you should change lines like:

if _gap['from'] == None

to:

if _gap['from'] is None

zip()/izip()

Let's take a look about what zip() does:

>>> x = [1, 2, 3]
>>> y = ['a', 'b', 'c']
>>> for num,ch in zip(x,y):
...     print num,ch
...
1 a
2 b
3 c

itertools.izip() is just the generator version of zip in Python 2 (like xrange() for range()). So instead of:

for i in xrange(len(flags)):

You may want to do:

from itertools import izip

for flag,time_stamp in izip(flags,ts):
    # ...

Don't pile imports

Is usually a better practice to import each package on its own line (it really helps readability). So, in your case, this will be better:

import logging    # I usually import logging as first
import numpy as np
import datetime
import time

Python has a very flexible syntax (as you've surely noticed), use it smartly and do not abuse of it.

& vs and

You have this line:

a = (ts >= g['from']) & (ts <=g['to'])

Are you sure you weren't looking for:

a = (ts >= g['from']) and (ts <=g['to'])

Or better:

a = g['to'] <= ts <= g['from']

_gap: unPythonic name

Your gaps_from_flags is full of _gap, self._gap might be a "private" attribute of an object, but _gap is a very strange name, if it's a gap just call it gap!

numpy.array creation

I would suggest a numpy tutorial.

After reading it, you may want to change this line:

flags = np.array([False]*len(ts), dtype=bool)

with:

flags = np.zeros((1,len(ts)), dtype=bool)

Let's talk about Design

Now that we cleared some things a bit, let's talk about your design. As I stated at the beginning I don't fully understand what you're doing, so fell free to provide more information, correct me if get things wrong, etc... etc...

First: go read The Zen of Python if you haven't already and then come back. Have you read it? Well! Now keep it mind every time you write a new line of code :)
Let me state this clear: I don't like those first four functions.
There's really a point of having one-line utility function? Are they really that useful if you'll have to replace one line with another one line?
If you had only one of them, with a complex one line and it was a real pain to repeat it all the times I might understand, but there are four of them and they are doing a very simple task: convertion.
So this leads me to: Why are you converting so much?
Do you really need it? I guess a better design will get rid of that. One conversion at the beginning and one at the end I'd say that's what one usually need with the proper design.
It seems like you're logging too much, but that's just my opinion thrown there.
gaps_from_flags is doing some really strange things. It seems that it's using a temporary gap dict. It looks very unpythonic. Borrowing from the Zen of Python I'd say that is ugly, complex and readability counts.
If I get what you're trying to do, you could use itertools.groupby(), probably something like this:

res = []
for k,g in itertools.groupby(zip(flags,tp), lambda x: x[0]):
    time_stamps = list(g)
    res.append({'from': time_stamps[0], 'to': time_stamps[-1]})

There's still way room for improvement in the above example, but as I said it's just a wild guess and an example. (Probably it doesn't even perfectly fit your flagging system).
Once again this leads me to think that you could probably get rid entirely of your flagging system. It looks painful to maintain. Is it really necessary? Perhaps there's a better design for what you're trying to do.
It seems like you're using numpy arrays like simple lists. There's a particular reason for using numpy here? And remember that: "premature optimization is the root of all evil".
You asked if it's ok to keep a set of function in an OO project. Well, the answer for Python is surely: Yes!


Memory issues when copying JPEG into bmp

If you need comments to document the flow of your method, then you're doing it wrong. Obviously this needs to be split into much smaller methods, each dedicated to their own logic.

That was you could move the three lines below //Read original JPEG to a method of their own that would return a BitmapSource, and you could encapsulate imageSource in a using block (considering it's an IDisposable).

Same for imageOutput: another stream you're not properly disposing of.

Quite frankly, I'd move everything inside the foreach into a class of its own and start refactoring from there.

I had to look up what this does:

string dirPath = file.Insert(file.LastIndexOf('\\'), "\\ripoffs");

I can't help but feel that this is a hacky way of something that should be done with for instance FileInfo and Path etc;

Consider this (I'm assuming file is a global variable of the class that contains all of the code in the foreach):

    private string GetResultPath()
    {
        var fileInfo = new FileInfo(file);

        var directoryPath = fileInfo.DirectoryName;
        var newDirectoryPath = Path.Combine(directoryPath, "ripoffs");

        Directory.CreateDirectory(newDirectoryPath);

        var fileName = fileInfo.Name.Replace(fileInfo.Extension, string.Empty)
                                   + "_ripoff"
                                   + fileInfo.Extension;

        return Path.Combine(newDirectoryPath, fileName);
    }

Yes, that's longer, but it's also much clearer and informs the next developer who looks at that code what it does.


Check string(line) in a file and send email

The else-pass construct is unnecessary. The else clause is not required. Leaving it of has the same result as what you have now.

You loop over the same file twice. Instead you can check the line for both messages in the same loop.

for line in open("status.txt"):
    if "Slave_IO_Running: Yes" in line or "Slave_SQL_Running: Yes" in line2:
        print "match",line
        i=i+1

However, the above change points out a potential bug. We don't have any information about what the contents of status.txt are. If it is possible for either of those strings to appear more than once, the code as posted (and my above update) could find two matches without finding a result for IO and SQL.
1

sql_found = false
io_found = false
for line in open("status.txt"):
    if not io_found and "Slave_IO_Running: Yes" in line:
        print "match",line
        io_found = true
    if not sql_found and "Slave_SQL_Running: Yes" in line:
        print "match",line
        sql_found = true

if not sql_found or not io_found:
    # send email

If the status file is long, you can break out of the loop after both lines have been found. This would prevent unnecessary work when you already know the correct information.

i is not a good variable name. It does not convey any information about how it is being used. In addition, i is widely accepted as the variable name for indexing in a loop. In this code you are looping, but i is being used for something else. Changing the name will prevent any confusion.

You can use the with construct to ensure the file is closed when you are done with it.

with open(status) as f:
    for line in open("status.txt"):
        # operate on a line

This is a short running script, so it is not a huge deal, but it is a good practice to get into when you move to writing longer applications.
While this is a short running

You never use sys, os or email.Utils. These imports can be removed.

1: If we extrapolate on the idea that the line might show up more than once, that could also mean that the file could contain a Yes line followed by a No line. If this is the case, this simple loop logic would no longer be sufficient.


Scheme function to duplicate every element of a list a specified number of times

I think you need to decide weather to repeat only on the first level of the list, or if you want to do a tree walk for lists inside lists. As is, this code produces a weird combination of both in an exponential explosion of the list, The following sample returns over 2 million leaf elements for an input of length 26 and a repeat of 10.

(leaf-count (super-duper '(a (b (c (d (e f g (h i) j k) l m n o) p q ) r (s t (u v) w ) x y) z) 10))
->> 2576420

(define (leaf-count Tree)
  (cond ((null? Tree) 0)
        ((not (pair? Tree)) 1)
        (else (+ (leaf-count (car Tree))
                 (leaf-count (cdr Tree))))))


Convert big collection into simple array

Yes. Use array.reduce and use an object.

const a = data.reduce((items, item) => (items[item.id] = item.name, items), {});

// a = {1:{...}, 2: {...};

You can still use the bracket notation to access the items, i.e. a[id].

A problem with using IDs as array indices is that you introduce gaps in the array. You also get a false array length. Take the following example:

const a = [];
a[999] = {/* User data */};
a.length // 1000;

You only added a single item, with id "999" but now the array reports 1000 in length. Items 0 to 998 are actually empty.


Using Biopython, I would like to optimize this code

First of all, read PEP8 (all of it!) and adhere to it. This is the de facto standard of Python code.

In the following, I’ll tacitly assume PEP8 as given.

Secondly, it would help if you had actually written what the expected output looks like. Given your input file, the script produces empty output.

I don’t understand what the while loop is supposed to do. align represents a single alignment record – you are reading a sequence file which contains multiple sequences. Furthermore, what is align[:, n]? Did you maybe intend to access the seq sub-object?

Likewise, the SNP method doesn’t at all make clear what its function is. And it implicitly uses global variables. This is error-prone and unreadable: use parameters instead. The function also accesses some object align[y] which won’t exist when y > 0, because AlignIO.read only reads a single alignment.

Furthermore, if you’re handling CSV files, I’d strongly suggest using the csv module. It’s not really less code in your particular case but it provides a more uniform handling and makes the code easily extensible.

Just to show what this could look like when done cleaner, here’s the production of the first file. I’d love to show the full code but I really don’t understand what the code is supposed to do since it doesn’t work for me, and I’m unfamiliar with the function of align[:,n] (and I think there’s an error in the access to align, anyway.

#!/usr/bin/env python

import csv
import itertools
import sys
from Bio import AlignIO

def snp(line, alignment, n, base, pos):
    """Documentation missing!"""
    id = alignment[pos].id.rsplit('|')[3] # why rsplit?
    return [ str(n + 1), line[0], id, base ]

def main():
    # TODO Use command line argumnents to provide file names

    alignment = Bio.AlignIO.read('HPV16_CG.aln.fas', 'fasta')

    with csv.writer('test.csv') as out:
        for n in range(len(alignment[0])):
            line = align[ : , n]
            for pos, base in line:
                if line[0] != x:
                    out.writerow(snp(line, alignment, n, base, pos))

if __name__ == '__main__':
    sys.exit(main())

In this code I tried to give the variables meaningful names but – again, since I don’t know what this is supposed to do – I had to guess quite a lot based on usage.

And by the way, range(len(x)) is actually kind of an anti-pattern but I can’t for the heck of it remember the “correct” usage (and even the documentation advises this).


I'm going to go down through the code line by line. I may be harsh at times, but remember, I say these things so that you might become a better programmer.

Sub dogame()

The sub name is a bit hard to read. I personally like the .Net capitalization standards where methods are PascalCased. Isn't DoGame easier to read? Also, get into the habit of explicitly declaring scope.

Application.Visible = False

I like that you're hiding the Excel instance from the user, but what happens if an error occurs? Without an error handler to regain control and make Excel visible again, you'll end up with an instance of Excel that you can only kill via the task manager.

loadedgame = False

Remember those naming conventions I mentioned earlier? Variables should be camelCased. So, loadedGame. However, I think it's easier to read as isGameLoaded.

The next thing I want you to do is start using Option Explicit in all of your vba code. It forces you to declare all of your variables. This will turn typos into compile time errors. It's wonderful. Trust me, just do it.

Lastly, booleans default to false, so if you declare the variable using a Dim statement, there is no need to explicitly set it to false.

To recap so far:

Option Explicit

Public Sub
    On Error GoTo ErrHandler

    Dim isGameLoaded As Boolean

    Application.Visible = False

    '...

    Exit Sub

ErrHandler:
    Application.Visible = True

End Sub

Which brings us to the Do loop. Friend, that is just awful. You've intentionally created an infinite loop. Once the DoGame is called, it never exits. Never. The only way I can figure to kill this is to open the task manager and kill Excel.

What you should do is have a While loop that exits when the game is over. For example, consider this code where GetGameState is a function that returns a boolean.

Dim gameOver As Boolean

While Not gameOver

    gameOver = GetGameState

End While

fminitScreen.Show
playgame

Again with the capitalization. This is hard to read. Not much else to say other than if you must use Hungarian notation for your user forms, then you should at least use Microsoft's recommended notation. fminitScreen should be frmInitScreen. But really InitializationScreen or StartScreen would be much better names. (I was going to provide a link, but it seems that MS has scrubbed that document from the face of the Earth...)

Skipping ahead a bit, there's this.

If Worksheets("options").range("B3").value = True Then

First, we have no clue what this value is, other than it's some option of some kind. I recommend creating a well named function to retrieve this value.

Secondly, the statement can be simplified by omitting = True. This is essentially what happens right now.

 Worksheets("options").range("B3").value = True
' get value from worksheet
True = True
' is true equal to true?
True
' enter if statement

That's why you can write this like this.

If Worksheets("options").range("B3").value Then

Same thing here. Simplify it.

 ElseIf loadedgame = True Then

ElseIf isGameLoaded Then

This is bad. Could these names be more generic?

    Dim obj As Object
    Dim obj1 As Object

What really makes this terrible is the type doesn't even give us a hint because you've declare them as generic objects. You could literally stuff any class instance you wanted to into those variables.

It looks like you're using obj to iterate the UserForms collection

   For Each obj In UserForms

So why not declare it as a UserForm???

Dim obj As UserForm

Or better yet

Dim frm As UserForm


Finds customer who live within 100km and output them to a text file

Generally I find the code very unstructured making reading it a bit confusing:
First you execute some code outside of a function to read the data from a file, then you define a constant (dublinOffice), then you define a variable (invitedArr), but don't use it in the next block of code, then you sort the data, then you define two functions, and finally execute one of the functions.
Further more the function closestCustomers both gets invitedArr passed an argument (and uses it as such) and uses it directly as a global variable.
Personally I'd have the main code calling functions first (after defining constants) and then define all functions at the end of the source code using function so that they are hoisted. Other people may define the functions first and then use them, but that is a matter of taste, as long it's not all mixed up.
More, smaller functions would also be helpful. Reading the data should be in its own function and closestCustomers does too much (filtering, converting the objects to strings, and calling writeInvitedCustomer). This would also make testing easier.
Using the array methods filter() and map() would help the code be more readable. Personally, I'd start with something like:
const inputFileName = "customers.txt";
const outputFileName = "output.txt";

const dublinOffice = {
  latitude: "53.339428",
  longitude: "-6.257664",
};
const maxDistance = 100;

const invitedCustomers = readCustomers(inputFileName)
  .filter(withinKms(dublinOffice, maxDistance ))
  .sort(userIdComparator)
  .map(formatCustomerForOutput); // `map` may be considered to be moved inside `writeInvitedCustomers`

writeInvitedCustomers(invitedCustomers, outputFileName);

function readCustomers(filename) {
  // ...
}

function withinKms(location, kms) {
   return (customer) => greatCircleDistanceCalc(customer.latitude, customer.longitude, location.latitude, location.longitude) <= kms;
}

function userIdComparator({user_id: userId1}, {user_id: userId2}) {
   return userId1 - userId2;
}

function formatCustomerForOutput({name, user_id}) {
   return `${name}:${user_id}`;
}

// etc.

One other point: I'm not familiar with node's WriteStream, but it looks wrong for me to assign the event handlers after using it by calling its write method. Can't write cause an error?
NB: This is probably not your choice, if this was an interview task, but I find the file format for customers.txt (multiple JOSN objects in one file) strange. A straight forward JSON array would make more sense.


Deduplicating value pairs between 2 columns

If val1 and val2 are comparable it is easy to find the distinct values, using set-based operations, by normalizing first and then taking distinct rows.

Given:

CREATE TABLE [TestTable]
(
    [TestID] INT NOT NULL IDENTITY(1,1),
    [Value1] NCHAR(1) NOT NULL,
    [Value2] NCHAR(1) NOT NULL,
)

INSERT INTO [TestTable]
    ([Value1], [Value2])
VALUES
    (N'A', N'B'),
    (N'A', N'C'),
    (N'B', N'A'),
    (N'B', N'C'),
    (N'C', N'A'),
    (N'C', N'B'),
    (N'D', N'C');

If you just need the values, and not the actual rows, you can use SELECT DISTINCT with a normalized CTE:

WITH [Normalized] AS
(
    SELECT
        CASE WHEN [tt].[Value1] > [tt].[Value2]
            THEN [tt].[Value2]
            ELSE [tt].[Value1] END [N1],
        CASE WHEN [tt].[Value1] > [tt].[Value2]
            THEN [tt].[Value1]
            ELSE [tt].[Value2] END [N2]
    FROM
        [TestTable] [tt]
)
SELECT DISTINCT
    [n].[N1] [Value1],
    [n].[N2] [Value2]
FROM
    [Normalized] [n];

Result:

Value1 Value2
------ ------
A      B
A      C
B      C
C      D

If you need the original rows instead you have to eliminate the duplicates yourself. This can be done using the normalized CTE and partitioning by the normalized values:

WITH [Normalized] AS
(
    SELECT
        CASE WHEN [tt].[Value1] > [tt].[Value2]
            THEN [tt].[Value2]
            ELSE [tt].[Value1] END [N1],
        CASE WHEN [tt].[Value1] > [tt].[Value2]
            THEN [tt].[Value1]
            ELSE [tt].[Value2] END [N2],
        [tt].[TestID],
        [tt].[Value1],
        [tt].[Value2]
    FROM
        [TestTable] [tt]
),
[Ranked] AS
(
    SELECT
        [n].[TestID],
        [n].[Value1],
        [n].[Value2],
        ROW_NUMBER() OVER (PARTITION BY [n].[N1], [n].[N2]
                           ORDER BY [n].[TestID] ASC) AS [Rank]
    FROM
        [Normalized] [n]
),
[Distinct] AS
(
    SELECT
        [r].[TestID],
        [r].[Value1],
        [r].[Value2]
    FROM
        [Ranked] [r]
    WHERE
        [r].[Rank] = 1
)
SELECT [d].[TestID], [d].[Value1], [d].[Value2]
FROM
    [Distinct] [d];

Result:

TestID      Value1 Value2
----------- ------ ------
1           A      B
2           A      C
4           B      C
7           D      C

As for performance, the iterative approach is, according to the execution plan in SSMS14, about 10 times slower. The set based solution is a table scan + a sort where as the execution plan for the iterative solution is a mess to look at.


Extraction of numbers from currency string

Simplify the overall logical flow

Notice the multiple else conditions in every if statement when some required condition is not true:

if (...) {
    if (...) {
        return currency / views;
    } else {
        return undefined;
    }
} else {
    return undefined;
}

These else blocks are repetitive.
It would be better to think of the logic as multiple levels of checks,
where you only return after all checks passed,
reaching the innermost level.
If at any checks fail,
execution drops out of the nested if blocks and fall back to the return statement of the function at the end, like this:

if (...) {
    if (...) {
        return currency / views;
    }
}
return undefined;

More readable without the map

Instead of this:

currency = currency.replace(/[,.]/g, function(k) {
    return map[k];
});

I would find it more readable to use two replace calls instead:

currency = currency.replace(/\./g, '');
currency = currency.replace(/,/g, '.');

You could even chain them together,
but that would be less readable.

Another reason why this is more readable is that in the original solution,
the map is defined far away from where it's used.
That can invite mistakes,
such as adding patterns in map but forgetting to adjust the regex in the replace call,
or the other way around.

Naming

reDigit is not a good name for /[\d\,\.]+/g.
The word "digit" suggests \d (0 ... 9), but you have more there.
How about reMoney or reMoneyDigits instead?
That would make it clear that it's more than just digits.

Validation

Are you sure all inputs are valid?
The code will work and return values for clearly bad input too, such as:

var currency = "hello20.002,03 €";
var currency = "20.0.0..2,03 €";
var currency = "20.a0b0c2d,03 €";
var currency = "20.002,03... €";

For the last example it will return NaN.

Will all this be ok in your application?

Even if you think such inputs are impossible, I think you should check for them.
One day when you might corrupted inputs,
which, in the absence of solid defenses could propagate in your systems and manifest as strange problems that are extremely difficult to debug.
It's better to catch problems early,
as close to their source as possible.

The only way you can assume the inputs are always valid,
if they have been prevalidated before reaching this code.
And in that case, this code should be in a private method,
only callable from the place where the validation was performed,
to guarantee that it can't be called with invalid data.

Dividing strings

I noticed a bit late, but curiously, the code is actually dividing strings:

'123' / 3
// -> 41

Ah, sweet JavaScript, only you can be capable of such madness.

You should use parseFloat for currency, and perhaps parseInt for view,
to make them proper numbers.
Note that this will change some things.
For example:

'123..' / 3
// -> NaN
parseFloat('123..') / 3
// -> 41


Some suggestions:

I believe the idiomatic way to declare custom exceptions is to inherit from Exception rather than BaseException, and to just use the no-op pass as the class body. I've not seen the __module__ = Exception.__module__ pattern before, but if that does what it looks like (making the class effectively part of the exceptions module) that's probably going to be misleading. It's not a generic error, after all.
It might be faster to put both upper and lower case characters in the dict than to use upper(). You could test this with timeit.
If you're processing a big string of Morse code you might want to use an iterator. That way the string is processed one word at a time, rather than having to split the entire text into a list in memory before starting to output anything.
Rather than parsing input() I would expect this sort of script to either read standard input or to accept a list of file path arguments which would each be read and converted.
If the script also accepted --encode and --decode parameters (possibly with --encode as the default) it could easily be used to script a conversion of any text.


C++14-ish code for creating q-grams of a string

Things I like:

(Mostly) a pretty neatly packaged, self-contained component.
Written primarily to emphasize simplicity

and let the compiler deal with making it fast

Things I don't like so well:

Q, PREFIX3, and SUFFIX3 are apparently globals (or maybe class variables?) so I can't see what they really are.
Subtle interaction: PREFIX3 and SUFFIX3 both (seem to) implicitly assume that Q = 3.
qword has a well-known meaning in Intel assembly language. Unless you're sure this will only be used by an audience that immediately knows what you intend, another name might be better.
Written non-generically, for no particularly good reason.
It almost seems like qwordify is really two separate things shoved together: a generic "generate all the results in a sliding window", and a specialized "generate all the qwords from a string".
If you can use the new string_view, it would be a good choice here.

Ignoring point 6 (since it's not really C++14), we could end up with code on this order:

// the generic algorithm:
template <class InIt, class OutIt, class size_type>
void window(InIt b, InIt e, OutIt d, size_type len) {
    for (auto s = std::next(b, len); s != e; ++s, ++b, ++d)
        *d = { b, s };
}

// The piece specifically for q-grams
std::vector<std::string> generate_qgram(std::string const &in, size_t q) {
    std::string input = std::string(q-1, '^') + in + std::string(q, '$');

    std::vector<std::string> words;

    window(input.begin(), input.end(), std::back_inserter(words), q);
    return words;
}

// and a little demo code:
int main() {
    auto ret = generate_qgram("INDEX", 3);

    std::copy(ret.begin(), ret.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}


C# enumerable property like .Any that accounts for nulls

My point of view is different depending on whether the the code that's returning null enumerables is a 3rd-party API or your own code.

3rd-Party

If the code that's returning null enumerables is a 3rd-party API, then I only have a few minor points to mention:

CLR is a very bad and misleading name for a class. In the .NET world CLR stands for Common Language Runtime, the part that's responsible for JIT-compiling CIL code (which all .net languages compile to), a bit like the JVM does for byte code / compiled Java.
I would have named Populated with a little Is prefix to read like IsPopulated, because I like Boolean functions/properties to read that way. But that's personal preference.

The implementation itself is nice & clean, nothing to say about it (other than the C# 6 trick in t3chb0t's answer); I like that you named the this parameter source, it lines up with other framework-provided IEnumerable<T> extension methods, e.g. LINQ. TSource seems a bit verbose when T would have been sufficient, but I like descriptive generic type parameters so I'd leave it as is.

In the sample code, you have this:

if (
    intList != null &&
    intList.Any()
    )

That looks terrible; an if condition should fit one single line:

if (intList != null && intList.Any())

Very long conditions that actually need to be multiple lines, should be extracted out of the if statement and into their own function with a meaningful name that captures the meaning of all these conditions:

if (IsValid(intList))

You get the idea; that's usually more commonly seen with LINQ queries and predicates though, but the concept is the same: if it's too much clutter to be readable, move it elsewhere and abstract it behind a meaningful identifier.

Your own

On the other hand, if the code that's returning null enumerables is under your control, there's a bigger issue.

Per Framework Design Guidelines 2nd Edition, p.256:

  DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead.

See this SO Q&A for more information about whether it's better to return null or an empty collection.

Instead of introducing an extension method to work around a serious design issue in your code base, you should be hunting down instances of IEnumerable<T>-returning methods and properties in that code base, and fixing them so that they return an empty enumerable instead of a null value:

return Enumerable.Empty<Foo>();

Then all you need to do is get rid of redundant but inoffensive null-checks everywhere in the code base, and new code wouldn't need any such null-checks.


You are right, this can be simplified, quite a lot actually!

First, I'm not sure I see the value of the j_utils object. The methods are simple enough that there isn't much value in creating a function for them, and I'm not sure I see the value of currying here.

That said, it cleans up nicely with arrow functions.

const j_Utils = {
  getValueOf: json => key => json[key],
  hasKeyOf: json => key => json.hasOwnProperty(key)
}

Now the getMappedData function, if I'm not mistaken you currently have a lot more if statements that essentially follow this pattern:

if (hasKeyOf(serverKey)) {
  result[clientKey] = getValueOf(serverKey)
}

This is a great opportunity to use some array methods to move your code into configuration. Here's one way to do it.

function getMappedData(data) {
  var clientServerMapping = [
    { client: 'clientFromDate', server: 'serverFromDate' },
    { client: 'clientToDate', server: 'serverToDate' },
  ];

  const getValueOf = j_Utils.getValueOf(data);
  const hasKeyOf = j_Utils.hasKeyOf(data);

  return clientServerMapping
    .filter(item => hasKeyOf(item.server))
    .reduce((carry, item) => {
        carry[item.client] = getValueOf(item.server);
        return item;
    }, {});
};

And here's the method without requiring the j_Utils helpers.

function getMappedData(data) {
  const clientServerMapping = [
    { client: 'clientFromDate', server: 'serverFromDate' },
    { client: 'clientToDate', server: 'serverToDate' },
  ];

  return clientServerMapping
    .filter(item => data.hasOwnProperty(item.server))
    .reduce((carry, item) => {
      carry[item.client] = data[item.server];
      return carry;
    }, {});
}

let clientData = getMappedData({
  'serverFromDate': '15/07/1988',
  'serverToDate': 123
});
console.log(clientData);

Lastly, I didn't take this approach as your keys might differ, but if all that changes between your object keys input and your object keys output is the word 'server' to 'client', you could just loop through, replacing each key, something like the following.

function getMappedData(data) {
  const result = {};

  Object.keys(data).forEach(key => {
    result[key.replace('server', 'client')] = data[key];
  });

  return result;
}

let clientData = getMappedData({
  'serverFromDate': '15/07/1988',
  'serverToDate': 123
});
console.log(clientData);


When I want to cache some file, I'm typically doing it similar to your solution.

However, you're able to do most of this with built-in functionality, making the code a lot shorter:

<?php
// Some URL for testing
$url = 'https://www.google.de/favicon.ico';

// Time to cache the files (here: 10 minutes)
define('time_to_cache', 600);

// Create a local file representation
$local = './cache/' . urlencode($url);

// Determine whether the local file is too old
if (@filemtime($local) + time_to_cache < time()) {
    // Download a fresh copy
    copy ($url, $local);

    // Store headers in case we need them (see alternative below)
    file_put_contents($local . '.hdr', join($http_response_header, "\n"));
}

// Solution 1: Redirect to the local cache file
header('Location: ' . urlencode($local));
exit();

// Alternative: Send headers and the actual file
// Note that this might cause problems, e.g. due
// to cache fields and the like.

// Read and send headers
foreach(file($local . '.hdr') as $line)
    header($line);

// Read and send the actual file
readfile($local);

This doesn't include any error handling though.

For error handling, you might just want to check the results of the copy() operation. There's no need to request headers in advance or doing anything like that, since that will essentially delay you twice.

Regarding your implementation above:

Don't check the headers first. Just try downloading the file. This will take the same time. If you request headers first, you'll do two request, each of which might delay you by the mentioned 200-300 ms.
I've used urlencode() to create a working local filename. This might not be perfect depending on your actual file system though.
Don't check whether your local file exists first; you don't have to. You can just prepend filemtime() by an @, which will keep it from outputting any error messages and still return 0 in case the file doesn't exist (which will simply be interpretes as the file being ancient).
Why do you read the JPEG from your local disk and then reencoding it as a new image to be sent to the browser? Just send the actual file contents (or redirect the browser). The following will do the same without reencoding the image:

header('Content-type: image/jpeg');
readfile($local);


String compression algorithm using functional JavaScript

Style notes

Not putting {, } around single line statement blocks is a bad habit. Always delimit statement code blocks.
In compressCharacters newArray should be a constant. In groupCharacters arr should be a constant.
Consistent naming is important. Your naming is all over the place. You call a string, characters (in compressCharacters), string (in compressString), signature, and e in the forEach. A character you call element. You abbreviate an array to arr in one function and call it newArray in another. Most of the names are describing the type and not the abstracted data that they hold.
Don't add useless or redundant code. In compressCharacters you create a variable result that you do nothing with. Not to mention that forEach does not have a return defined. Also result in groupCharacters is never used.
Don't declare variables outside the scope that they are to be used. newSignature is only used inside reduce but declared outside the callback.

Functional programing means that functions should not have side effect (change the state of anything outside the function's scope.) The reduce callback uses the array arr which breaks the no side effects rule. And the forEach pushes to arr which is also outside the forEach callbacks scope (use map or reduce in that case).
Applying the above you would get something like the following code.
const groupRuns = str => [...str].reduce((groups, char) => {
        const last = groups.length - 1;
        if (last < 0 || groups[last][0] !== char) { groups.push(char) }
        else { groups[last] += char }
        return groups;
    }, []);

const concatGroups = groups => groups.reduce((str, g) =>
        str + (g.length > 2 ? g[0] + g.length : g)
    , "");

const compressString = str => concatGroups(groupRuns(str));

const signature = `aabcbbbaaaaaabcccccdddddddbbba`;
compressString(signature);

Note that rather than add numbers to groups of size 2 the group must be 3 or larger.


You can use something like the following:

with open(file_eval_id) as f:
    eval_ids = [int(line) for line in f]

The code assumes, that ID is the only thing in the line.


Circle Summation (30 Points) InterviewStree Puzzle cont

#include <iostream>
#include <algorithm>
#include <iterator>
#include <stdio.h>

int main ( int argc, char **argv) {
    int T; // number of test cases
    std::cin >> T;
    for ( int i = 0 ; i < T; i++) {
        int N; // number of childrens
        std::cin >> N;
        int M; // number of rounds
        std::cin >> M;

Why split this across two lines instead of std::cin >> N >> M;?

        long long childrens[50];

I missed this in my first submissions and tried using 32 bit integers. It didn't work so well...

        for ( int j = 0; j < N; j++ )
            std::cin >> childrens[j];

        int pos = 0;
        for ( int i = 0; i < N ; i++) {
            long long childs[50];
            for ( int j = 0; j < N; j++ )
                childs[j] = childrens[j];
            for ( int j = 0; j < M; j++) {
                int left  = ( pos     == 0)  ? N - 1  : pos - 1;

You can use left = (pos + N - 1) % N which works thanks to modular math.

                int right = ( pos + 1 >= N ) ? 0      : pos + 1;

You can use right = (pos + 1) % N

                childs[pos] = (childs[pos] + childs[left] + childs[right])% 1000000007;
                pos++;
                pos   = ( pos >= N ) ? 0 : pos;

You can use pos = (pos + 1) % N

            }
            std::copy(childs ,childs + N ,std::ostream_iterator<long long>(std::cout," "));
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
    return 0;
}

Generally, writing brute force solutions for a site like Interviewstreet is a waste of time.   Its not like you can write your brute force solution, and then optimize it so that it will run fast enough. You need to come up with a completely different approach.

Since Interviewstreet is trying to test your abilities I'm not going to share my solution. (Unless you have a solution for the Meeting Point problem, then I'll trade :P) But I will give a hint: think back to linear algebra.


There's not much code, however, I'd change input_lines in the following ways:

  Only display prompt while reading first line.

If you're only going to do something once, then just add it as an initial return.
It's simpler IMO to have a try that wraps the entire code of the function, this way you know it will keep doing something until EOFError is raised. Rather than possibly do something on each iteration.

As noted in the comments by OP, you can instead use contextlib.suppress, which can make the code easier to read.
You may want to use yield from and iter, if you think that's cleaner to read than a while loop.

This can result in either of:

def input_lines(prompt=None):
    try:
        if prompt is not None:
            yield input(prompt)
        while True:
            yield input()
    except EOFError:
        pass

from contextlib import suppress

def input_lines(prompt=None):
    with suppress(EOFError):
        if prompt is not None:
            yield input(prompt)
        yield from iter(input, None)


Project Euler #16 - Sum of all digits of 2^1000

This looks good. I assume this results in correct answer.

What you can use instead of converting to String and back to int is to use divideAndRemainder method with 10 since we need to treat this as a base 10 number.
This method is available in BigInteger for situations like this.
We can also directly use BigInteger constants such as TWO and TEN.

Alternative Implementation

BigInteger big = BigInteger.TWO.pow(1000);
String num = big.toString();
System.out.println(num);

int result = 0;
BigInteger[] components;

components = big.divideAndRemainder(BigInteger.TEN);
while (components[0].signum() != 0) {
    result += components[1].intValue();
    components = components[0].divideAndRemainder(BigInteger.TEN);
}
result += components[1].intValue();
System.out.println(result);

I've used signum method here to check if result after integer division is zero.
Note: This seems to be creating lot of objects.

Benchmark with JMH

After the some discussion in comments with @TorbenPutkonen, I agreed with TorbenPutkonen that alternative implementation might be creating more objects. However there is no way to see which implementation performs faster without doing a benchmark.

public class X {

    public static void main(String[] a) throws Exception {
        org.openjdk.jmh.Main.main(a);
    }

    @State(Scope.Benchmark)
    public static class BenchmarkState {
        BigInteger multiple =  BigInteger.TWO.pow(1000);
        public BenchmarkState() {
            System.out.println(multiple);
        }
    }

    @Benchmark
    @Warmup(iterations = 5)
    public int withDivide(BenchmarkState x) {
        BigInteger[] components;
        components = x.multiple.divideAndRemainder(BigInteger.TEN);
        int result = 0;
        while (components[0].signum() != 0) {
            result += components[1].intValue();
            components = components[0].divideAndRemainder(BigInteger.TEN);
        }
        result += components[1].intValue();
        return result;
    }

    @Benchmark
    @Warmup(iterations = 5)
    public int withChars(BenchmarkState x) {
        String num = x.multiple.toString();
        int result = 0;
        for(char i : num.toCharArray()) {
            result += Integer.parseInt(String.valueOf(i));
        }
        return result;
    }

    @Benchmark
    @Warmup(iterations = 5)
    public int withCharsNumerical(BenchmarkState x) {
        String num = x.multiple.toString();
        int result = 0;
        for(char i : num.toCharArray()) {
            result += Character.getNumericValue(i);
        }
        return result;
    }

    @Benchmark
    @Warmup(iterations = 5)
    public int withCharAt(BenchmarkState x) {
        String num = x.multiple.toString();
        int len = num.length();
        int result = 0;
        for(int i = 0; i < len; i++) {
            result += Integer.parseInt(String.valueOf(num.charAt(i)));
        }
        return result;
    }

    @Benchmark
    @Warmup(iterations = 5)
    public int withCharsNumericalCharAt(BenchmarkState x) {
        String num = x.multiple.toString();
        int len = num.length();
        int result = 0;
        for(int i = 0; i < len; i++) {
            result += Character.getNumericValue(num.charAt(i));
        }
        return result;
    }
}

# Run complete. Total time: 00:21:29

Benchmark                    Mode  Cnt       Score      Error  Units
X.withCharAt                thrpt  200  117285.320 ±  644.505  ops/s
X.withChars                 thrpt  200  116882.706 ±  779.233  ops/s
X.withCharsNumerical        thrpt  200  110849.659 ± 3901.095  ops/s
X.withCharsNumericalCharAt  thrpt  200  121480.705 ± 2040.597  ops/s
X.withDivide                thrpt  200   11306.787 ±   35.711  ops/s

This concludes that original version is roughly 10x faster than divideAndRemainder
Original version is also slightly faster than using getNumericValue by itself.
However we can use charAt and avoid creating a character array too.

Why is using divideAndRemainder slow?

toString method of BigInteger uses a faster algorithm to create the string representation.
divideAndRemainder creates lot of BigInteger objects.


Calculate Hand Value in a Blackjack Hand

This function doesn't have any really obvious inefficiencies, so I assume we're looking to shave off every possible clock cycle...

Sometimes it's faster to use Python's built-in aggregation functions than to use a for loop.  Here's how you could use sum and any:

def value(self) -> int:
    value = sum(card.value for card in self.cards)
    if value <= 11 and any(card.rank == "A" for card in self.cards):
        value += 10
    return value

Note the ordering of the and expression to make sure that the any iteration only happens if the value condition has already been met!

If you have flexibility over the representation of the cards, you might try making the rank an Enum with integer values.  I'd expect comparing two integer enums to be just a smidge faster than comparing two strings.


Java has Integer.highestOneBit that can make this a bit simpler:

int highestOneBit = Integer.highestOneBit(value);
if (value == highestOneBit) {
    return value;
}
return highestOneBit << 1;


Can this iterating javascript code be optimized?

You should cache all methods calls - JS is interpreting language and
there is no optimizers to help you, therefore, each time you call
method, get element from array etc, you are actually asking JS
engine to DO this for you.
Concluding that someObjArry is an array, should avoid using loops with "in" statements - use standard loops with indexes instead. "in" statement walks through all object's properties, not collection's elements, so it's just future maintenance "watch-out".
Property "displayName" of object "someObj" seems like of a string type - try using strong type comparisons if possible (not an optimization, just a good practice)
Cache as much as you can

var someArray = MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry,
    arrayElement;

for(var i=0, $length = someArray.length; i< $length; i++){
    arrayElement = someArray[i].someObj;

    if (arrayElement.displayName === 'some value'){
        console.log(arrayElement.someId);
    }
}


Layout of two different styles of event labels with CSS

There's a difference between magic numbers and values derived from calculations.  A lot of your numbers aren't really magic, you just don't know the formula to get those values.  You can start by creating variables of the things you know are going to impact your values (eg. font-size, line-height, etc.).  Then you start looking for a formula you think will create your magic number.  When it works, change one of the values and see if it still works.  The width for $month is almost bulletproof, but the rest need help:

$padding: .5em;

$day-size: 2.25em;
$day-line-height: 1.5em;

$month-size: 1em;
$month-line-height: 1em;

body {
  padding: 10em;
}

time {
  outline: 1px solid;
  display: block;
  width: 3.5em;
  padding-left: $day-line-height;
  text-align: center;
  position: relative;

  .month {
     $width: $day-size * ($day-line-height / 1em);
     font-size: $month-size;
     transform: rotate(270deg);
     position: absolute;
     top: ($day-line-height - $month-line-height) / 2 + 1;
     left: ($width / $day-line-height - $month-size) * -1 + $padding;
     width: $width;
     text-align: center;
     line-height: $month-line-height;
     outline: 1px solid blue;
  }

  .day {
     font-size: $day-size;
     line-height: $day-line-height;
     outline: 1px solid red;
  }
}

http://codepen.io/cimmanon/pen/BcraL?editors=010

If you look at the markup in the pen, you'll notice that it is a little different than what you're doing:

<time datetime="2014-06-30">June 30</time>

<time datetime="2014-02-24">Feb 24</time>

<time datetime="2014-09-15">Sept 15</time>

<time datetime="2014-05-04">May 4</time>

The time element should not be treated like a span, it has special meaning.  If you don't have a valid date/time format (eg. 2014-05-04), then you need to use the datetime attribute to contain that information.

If you have two distinct times (such as your starting and ending time), then you should have two time elements:

<time datetime="2014-07-17T13:00Z">13:00</time>-<time datetime="2014-07-17T14:30Z">14:30</time>

Reference: http://www.brucelawson.co.uk/2012/best-of-time/

I don't feel that the article element is the appropriate choice for this type of information.  An article is supposed to be for content that can be removed from the surrounding content and still make sense.  An ordinary div or a table would be a better choice:

Event Information

        When
        Tomorrow

        Where
        The Library

        What
        Chess Club Meeting

If the th/caption elements are cramping your style, just hide them.  Tables don't have to look like tables.  It's a bit rough, but you get the idea:

http://codepen.io/cimmanon/pen/Daxkb


Storing a rectangle

The Image stores the parameters to create a rectangle. Those values are not used for anything else in the lifetime of the object, except to create the bounding rectangle when needed. You could instead just store the rectangle itself, so could simply return it when needed.

Pointless local variables

Many of the local variables are pointless, you could skip declaring and assigning to them and simply return values directly, for example:

func (p *Image) At(x, y int) color.Color {
    return color.RGBA{
        p.image_[x][y][0],
        p.image_[x][y][1],
        p.image_[x][y][2],
        p.image_[x][y][3],
    }
}

Naming

The _ suffix in Image.image_ is unusual. I suggest to simply drop the suffix.

The name i is most often used in simple counting loops, I suggest to avoid using it for other purposes. A good short name for an image instance could be img, for example.


Directed Acyclic graph implementation in Ruby on Rails

You should take a look at the through: option of has_many:

class Node
  has_many :parent_edges, class_name: "Edge", foreign_key: :child_id
  has_many :parents, through: :parent_edges

  # ditto for children
end

Getting at edge_properties depends on the version of Rails you are using.


Here are some points to consider:

Your end variable is declared without a var, so that it's leaking into the global namespace. Don't do that.
As it stands now, your obj isn't used anywhere in the code. I'll assume it's not applicable here.
Instead of manually keeping count of your iteration, use the % (Modulus) operator to calculate your rows.
jQuery's append method doesn't deal with code fragments the way you seem to think it does. append("
") actually appends a whole table, not just an opening tag (that's not even possible).
Access to the DOM is not free. Every time you hit the DOM you incur some overhead. Try keeping DOM modification to a minimum.
Unlike others, when dealing with a simple HTML construct such as this, I prefer to build my fragment from a concatenated string since it's much faster.

With all that in mind, here's how I would do it:

var arr = ["earth", "mars", "jupiter", "saturn", "venus", "argus", "pluto", "janus", "canary", "orange", "butter pineapple", "eventual bliss"],
    snippet = '

';

$.each(arr, function(i, val) {

    if (i % 3 == 0) snippet += '

';

    snippet += '<input name="finalcategory" type="radio" value="' + val + '" />	' +
               '' + val + '	';
});

snippet += '

';

$("#radio_container").append( snippet );

See it here in action: http://jsfiddle.net/DWcSN/

The code above works, but the text is not associated with the radio button in any way.

To remedy that, consider wrapping labels around your radio buttons:

snippet += '' +
               '<input name="finalcategory" type="radio" value="' + val + '" />' +
               val +
           '	';

See it here in action: http://jsfiddle.net/DWcSN/1/ (clicking the text activates the corresponding button).

P.S. style3 is not very descriptive. You should consider coming up with a more intuitive naming convention.


I think it is very concise, well done!

For this small problem this will be fast enough.

Code only

I would only add braces around the if body:

 for (int i = 1; i < 1000; i++) {
        if (i % 3 == 0 || i % 5 == 0) {
            sum += i;
        }
 }

For performance, please note that modulo is kind of slow. You could implement two variables that hold multiples of 3 and 5.

    public static void main(String[] args) {
        int threes = 0;
        int fives  = 0;
        int sum    = 0;
        for (int i = 1; i < 1000; i++) {
            if (i>threes)
                threes+=3;
            if (i>fives)
                fives+=5;
            if (i == threes || i == fives )
                sum+=i;
        }
        System.out.print(sum);
    }

Math

Better will be to go purely mathemathical:

  The formula for the sum of an arithmetic series is:

  Sn = (n/2) * (a1 + an)

  Sn = the sum of the n terms in the sequence.

  a1 = the first term in the sequence.

  an = the nth term in the sequence.

We need to determine the number of items 'n' in the sequence. For simplicity I name this occurrences.

This is calculated as dividing the limit - 1 by number. Because the integer division, it is rounded down.

The number an is the last multiple that fits below the limit, which is equal to occurrences * number

Calculate the sum om the series for threes, fives and fifteens. The solution is:

Sum(threes) + Sum(fives) - Sum(fifteens)

In code:

public static int sum( int limit, int number )
{
    int occurrences = (limit-1) / number;
    //Below is a rewrite ( thnx to Olivier Grégoire) of:
    // (int) ( ( occurrences / 2.0 ) * (  occurrences * number + number) );
    return number * occurrences * (occurrences + 1) / 2;
}
public static void main( String[] args )
{
    System.out.println(  sum(1000,3) + sum(1000,5) - sum(1000, 15));
}


Printing out prime numbers from an array given a max number

Here it is using Prime#prime?:

  Suppose I want to get all the prime numbers less than 9

require 'prime'

a = (1..12).to_a
p a.select{|e| e.prime? and e < 9 }
# >> [2, 3, 5, 7]

Here is a method

require 'prime'

def prime_below_max(a,max)
   a.select{|e| e.prime? and e < max }
end

ary = (1..12).to_a
p prime_below_max(ary,9)
# >> [2, 3, 5, 7]


your code looks very good, there are only minor issues:

1) naming

since you don't create any instances of FragmentsManager you should consider to rename it to FragmentsUtility. An Utility class provides methods to help you with your code while a Manager is an instance that does the work for you.

boolean should beginn with prefix is (or rarely as an alternative has/can/should) (in Java it's convention to use camelCase)
so rename your boolean add_to_backstack into boolean isAddedToBackstack rather (btw. in java it's convention to use camelCase)

2) comments

remove commented code!

3) javadoc

you provide some javadoc on the addFragment methode which is very crude - get things done and finish it!

the same applies to replaceFragment.


Why not take advantage of the RESTful architecture of the internet? I suggest you have the code generate a static page and set the expires header on that resource (or set of resources) to the end of that day (considering your audience's time zones, I guess). This might help.

Sorry, if I had experience with heroku or flask I would provide code or more details.


Wrapping std::bind call in a function returning std::function

I see a few potential problems that you might want to address.  First, I'll have to say that it's not entirely clear what problem you're trying to solve. That is, it's not clear why one wouldn't just call func(s) as in your very first example.

Handle const functions and objects

The my_binder call doesn't currently handle const functions.  For example, we can easily declare Master::func const.  However, the template fails in this case.  Things only get worse if we also make go const and then declare the instance m of Master to be const.  I'm not just sure how to fix that.

Pass const string reference

A more minor issue is that the second argument to call_function ought to pass the string by reference to avoid creation of a temporary and can be const.

Consider using a lambda instead

Here's an implementation that doesn't use templates and may address your need.

void Master::go() const
{
    const std::string s("hello");
    [&](){func(s);}();
}

That funny looking last line is both declaration and call of a lambda.  It (rather pointlessly in this case) captures all in-scope variables by reference, takes no parameters and invokes func(s).  It then actually calls that lambda with no parameters.  It's a complex way of just saying func(s) but then, so was call_function(my_binder(this, func), s); so I am hoping that wherever it made sense to do the latter, it may be better instead to use a lambda.

To me, this is much simpler and easier to understand, especially since you're using C++11.


Only using randint, create a random list of unique numbers

Your question reminds me of a beautiful page that visually explains the efficacy of shuffling.

But here are the two main problems with your algorithm:

Your memory usage is bad, this is as you're not performing the shuffle in-place.
As you have to make a new list, to keep the old intact and to make the new you need \$O(n)\$ memory.
If you instead performed the shuffle in-place then you'd only need \$O(1)\$ memory.
You're removing from the middle of an array. As Pythons lists are internally arrays,
when you remove anything that is not the item at the end, you have to shift all the previous data.
This leads to list.pop having a worst case of \$O(n)\$ performance.

If you take this with the fact that you have to perform this action \$n\$ times, then you can quickly see this algorithm is \$O(n^2)\$.

Both the problems above have the solution of performing the shuffle in-place.
To do this you want to swap the chosen item with the current index.
So if we're on the first item, and we randomly pick the index four,
then we'll swap the item at index zero and four.
Or in Python:

i, j = 0, 4
numbers[i], numbers[j] = numbers[j], numbers[i]

Now that we can perform the swapping efficiently,
you'd have to change what indexes you pick, when using randint.
If we're on index 4 of 8, then you'd not want to pick an index below four.

I'd change your program to have a function shuffle that takes an array as input, swaps it in-place and returns None.
And for you to use this rather than get_un_sorted.

And so you should be able to get something like, the Fisher–Yates shuffle:

def shuffle(l):
    for i in range(len(l) - 1):
        j = randint(i, len(l) - 1)
        l[i], l[j] = l[j], l[i]

Finally you could use randrange rather than randint as it's a short hand for having the upper bound be non-inclusive.


Maybe a late response but I'm new to codereview but not to AppleScript. The problem with AppleScript and scripts that stays open is that they leak memory. Why? I just blame it on AppleEvents. It's a nice feature, it really is, but it does eats memory somehow. So the longer the script will run the more memory it will eat. Eventually, maybe after 6 months, your fans will start blowing for now reason and the mac becomes significant slower. But maybe it does that after a day, a week or a year. It's hard to tell in AppleScript where and how much a script leaks.

To solve this there are several ways to do this. You can do it with cron (is since Tiger built inside launchd) with a shell script or create a new process of itself and quit. Either way they all remove the repeat loop out of the AppleScript and let that part be handled by other, much better, software. Note: using an idle handler inside AppleScript will eat memory too which should be the nicest solution instead of using a repeat and a delay.

My advise, is that the script won't be eating to much memory so I would spawn a new process of itself just over some time. You're waiting 10 seconds so 360 loops would be enough. You spawn a new process around every hour.

change the repeat to repeat 360 times and add the following code to the end of your AppleScript file.

  do shell script "osascript " & quoted form of posix path of
  (path to me) & " &>/dev/null &"

Note: User interaction (display or choose commands) is not allowed when a script is launched by osascript in Mountain lion or earlier. For any user interaction change the target to SystemUIServer or Finder for instance.


Solving jumbled letters using a given dictionary

Loop like a native

I highly recommend Ned Batchelder's excellent talk called "Loop like a native".

for i in range(0,len(possibility)):
    print possibility[i],

can be rewritten:

for p in possibility:
    print p,

Python 2 in 2018

It is probably a bad idea to write new Python 2 code in 2018. You should try to write it in Python 3.


Determine whether a list contains a particular sequence

As you said in your comments above, the first is the cleanest way you came up with.

Instead of writing your own logic, Python has a built-in library difflib that contains the SequenceMatcher class. You can use this to find the longest match between two iterables:

from difflib import SequenceMatcher

def contains(main_list, sub_list, junk=None):
    sub_len = len(sub_list)
    extended = main_list + main_list[:sub_len]

    sequence = SequenceMatcher(junk, extended, sub_list)
    return sequence.get_longest_match(0, len(extended), 0, sub_len).size == sub_len

My only qualm with get_longest_match is that its parameters are ALL positional arguments and are thus required. I would prefer the API assume we want the entire length of both iterables searched. Instead of using get_longest_match you could instead use the get_matching_blocks function (which returns tuples) then iterate through those until the corresponding tuple value is equal to sub_len.

By using SequenceMatcher you also get the flexibility to declare what 'junk' you want the class to ignore. So say you want to find the longest match between the two lists, but you don't care about 1 or 2. You would simply pass the lambda:

lambda num: num in [1, 2]

as the junk parameter.

Now that I've given my structure recommendation, I want to give some style pointers.

First of all, take a look at PEP8, the official Python style guide. It gives a great reference to how your code should look. Here are some places your code strays from the Python conventions:

Use descriptive variable names. Single letter variable names are typically frowned-upon. When naming, err on the side of being too descriptive instead of too brief.
Use underscores_in_names for basically everything in Python. The only aberration from this rule is class names which are written in PascalCase.

Also, variable and function/method names should be lowercase. Conventionally, uppercase names are saved for constants. So by convention, you L variable is considered constant.
Your spacing is quite nice; except for a few occasions where you place a single space after an opening paren and before the close paren. PEP8 actually labels that style as a pet peeve.
Multi-line statement happen. PEP8 purposefully takes a neutral stance on how those should be formatted. However, Python is quite lenient in terms of newlines in statements, so more than likely, there is a better way to format your multi-line statements without escaping the newlines.

def Contains2(L, s):
    L_extended = L+L[0:len(s)]

    return next((True for i in xrange(len(L))
                 if  L_extended[i:i+len(s)] == s), False)


Code / protocol comments under the code sections.

def read_file_blocks(file, extra_bytes=0):
    while True:
        data = file.read(BUFFER_SIZE + extra_bytes)

At least specify why the extra bytes are used and document what extra-bytes argument means.

def hmac_file(file, key):

Why would you go over the entire file and then dispose of the read bytes only to perform HMAC? You just processed all the blocks in memory! Why blake2b instead of one of the more common SHA-2 hashes?

#Use 4 bytes less than the nonce size to make room for the block counter

I'll bet that this isn't required; undoubtedly the counter is already included. Maybe you can point to a specific requirement to include a block counter every 4MiB?

hmac_key = nacl.hash.sha256(key + nonce, encoder=nacl.encoding.RawEncoder)

At least use HMAC instead of a hash to derive keys, the is a poor man's KDF.

output['key'] = base64.b64encode(key + nonce)

Sorry, output what? The key?

output['signature'] = hmac_file(encrypted_name, hmac_key)

CryptoBox uses an authenticated cipher. No need at all to HMAC it again.

  Algorithm details:
  Encryption:   Salsa20 stream cipher
  Authentication:   Poly1305 MAC


The prevalent answer is: No. (Funny enough, working with Office files seems to be a valid exception to the rule).

The problem is that you don't have type validation anymore, and any issues will reveal themselves at run time.

I'd say, if it's a small thing and it won't be touched or changed by people who might not know how it works, go for it (Even then, make sure you document this).

Otherwise, an Interface approach sounds like a better idea, like ChrisWue's comment said.


I think you want to flatten each child in turn:

private IEnumerable<MoveTreeNode> Flatten()
{
    yield return this;

    foreach (var node in Children.SelectMany(child => child.Flatten()))
    {
        yield return node;
    }
}

That way you won't flatten the whole tree first.

Edit:

It's more difficult to talk about things so let's look at some code. SelectMany is roughly equal to:

public static IEnumerable<TOut> SelectMany<T, TOut>(this IEnumerable<T> source, Func<T, IEnumerable<TOut>> selector)
{
    foreach (var item in source)
    {
        foreach (var subItem in selector(item))
        {
            yield return subItem;
        }
    }
}

So as you can see, we will definitely get all of the nodes and if you stop iterating before the end (e.g. by calling .First()) you will only call Flatten() on a single child.


Optimizing code from spectral subtraction algorithm

I don't have a clue about spectral subtraction, so just some minor, general notes about code:

public int fix(double val) {
    if (val < 0) {
        return (int) Math.ceil(val);
    }
    return (int) Math.floor(val);
}

It should be called truncate.
A few variables could be renamed to follow the Java code conventions.

Variables, parameters:

signal_in to inputSignal or signal
HW to hw
seg maybe to segments or segment (?)
Matrixseg to matrixSeg

Methods:

HammingWindow to calculateHammingWindow

(Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions and The Java Language Specification, Java SE 7 Edition, 6.1 Declarations).
This comments looks unnecessary:

// hamming window
double[] hammingWindow = this.HammingWindow(samplesPerWindow);

(Clean Code by Robert C. Martin: Chapter 4: Comments, Noise Comments)

The this. prefix also unnecessary.


Your input might be a String or an Array. Both of these support the :index method, so foo[-1] will give the last character of a string or the last element of an array. But if you test for it being an array, the solution won't work for strings when it otherwise would.
I don't think there's anything wrong with using ternary operators in ruby, as long as all three 'elements' are fairly short. More concise code is easier to read. See the Ruby Style Guide at https://github.com/bbatsov/ruby-style-guide#ternary-operator.


Returning boolean

A pattern

    if (condition) return true;
    return false

is to be avoided.

    return condition;

achieves the same in a much more transparent manner. In your case,

    return speechActivities.size() != 0;

Testing vs acquisition

Consider the situation: by the time you call getMicrophoneAvailable it might be available, but later on when your app actually needs it, it's been successfully claimed by some other app.

It means there is no point to test for availability. Acquire it as you need it:

    public static MediaRecorder getMicrophone(Context context) {
        ....
        try {
            recorder.prepare();
        } catch (IOException exception) {
            return null;
        }
        return recorder;
    }


Haskell game server auth: cookie key generate&check

As modifyIORef notes, use modifyIORef' for counters.

I would wrap the unsafe usage of unsafePerformIO into a safer interface.

withCounter :: (Int -> IO a) -> IO a
withCounter action = let counter = unsafePerformIO $ newIORef 0 in do
  i <- readIORef counter
  modifyIORef' counter (+1)
  action i

generateId = withCounter $ \date -> do
  time <- fromEnum . utSeconds <$> getUnixTime
  return $ time * 1000 + mod date 1000

The || logic doesn't seem to be in the Haskell code yet.

I wouldn't give a name to a private function used only once.

Many of your brackets are redundant. The hint tool can tell you this.

It seems you want to use some but not all of what you define in other code. The code that uses this could make a difference in the review.

Data.Unique may interest you for id generation if you do not actually care about your exact behavior.


Welcome! Let's look at your code:

I notice that you have code that appears to be part of a class, so I will be treating it as a class for the purposes of review. In your original code, you use a class to group all your operations together, but the class doesn't really serve a purpose (i.e. the method could exist independent of the class, with a name like is_prime). In your second version, you have two separate method, and while the encapsulation of different functionally is better, they are not connected in a meaningful way so it is not clear how you run the program. In both cases, a class is unnecessary: you could have a single function that prompts the user for a positive integer input, and another function that checks if a positive integer is prime or composite (which I will demonstrate below). Personally I store my input validation methods in a separate module that I've added to my PYTHONPATH, since it's useful for many different projects if you use the command line often.
Commenting in general on your goal to "check the input implicitly", I would say this is misguided, but I will also say that you can use a property decorator to implicitly check variables on assignment. However, as Michael mentions you still would need to loop to prompt input from the user until they enter valid input, so it's not really that usefully for input validation.

Now, if you're trying to validate input in Python, this SO answer provides a good primer on the subject.

Your check_digit method checks if the input is valid before the user actually enters any input. As mentioned in the above answer, while True and with an if valid: break is a better structure for this kind of validation.
Your userinput method is ambiguously named (you can't tell what it does from the name alone), and it's broken: it only checks if 2 is prime before breaking. You need to only check if the number is composite inside the loop, and return prime if a composite factor is not detected.

Here's code that demonstrates the principles I mention above:

def prompt_positive_number(message):
    while True:
        try:
            num = int(input(message))
            if num <= 0:
                message = "Please enter a positive number. "
            else:
                return num
        except ValueError:
            message = "Please enter a number. "

def is_prime(num):
    for i in range(2, num):
        if num % i == 0:
            return False
    return True

if __name__ == "__main__":
    user_input = prompt_positive_number("Check if a number is prime: ")
    if is_prime(user_input):
        print(user_input, "is prime!")
    else:
        print(user_input, "is composite!")

There's one more optimization I can use to make my code even shorter: using the built-in function any for is_prime:

def is_prime(num):
    return not any(num % i == 0 for i in range(2, num))

Or, reversing the equality check, all is even shorter:

def is_prime(num):
    return all(num % i != 0 for i in range(2, num))

Finally, commenting on the algorithm, there are more efficient ways to check if a number is prime; however, this is outside of the scope of my knowledge and you'd have to do your own research on that. Rather famously in the world of computational complexity, it was proved that primes is in P.


It's ok in regards of readability, but it can be shortened.

There is no need to create a dedicated trait FromIntConverter with implementations. All that can happen anonymously.

The convertInt function can take a function as implicit parameter:

def convertInt[T](i: Int)(implicit converter: Int => T) = converter.apply(i)

And all the implicit vals can become one-liners:

implicit def intToFloat(i: Int) = i.toFloat

implicit def intToDouble(i: Int) = i.toDouble

P.S. I discourage the use of int as variable name, that shouldn't collide with the Java type name.


There are two places where I would use var:
var conn = new MySqlConnection(ConnectionString.ConnString)
var complaint = new List<ComplaintModel>();

You no longer have to put braces around a using block, saving you one indentation level:
using var conn = new MySqlConnection(ConnectionString.ConnString);

Don't put the first parameter at the end of the line and the rest on a new line. Put the first parameter on a new line as well:
complaint.Add(new ComplaintModel {
    Date = _Date,
    ...

If you start the Query string on a new line, you can move it back one indentation level:
conn.Execute(
    @"INSERT INTO customer_complaints
    ...


Sorted linked-list in C (self-compiling)

All in all there's not much to criticize. Be sure to fix the bugs mentioned in the other answer, though!

Fail fast

struct node *new = malloc(sizeof(struct node));
new->priority = priority;

You do not check whether allocation succeeded.  Thus the next line will probably result in a crash in case malloc returned NULL.  But it could also continue to seem to be working, failing at a potentially completely unrelated point in your program.  That's the problem with undefined behavior. Thus, if you want an allocation failure to be a fatal failure, then you have to actually code such a failure mode:

void * malloc_or_die(size_t size) {
  void * pointer = malloc(size);
  if (pointer) {
    return pointer;
  }
  fprintf(stderr, "Fatal: failed to allocate memory of size %zu.\n", size);
  exit(EXIT_FAILURE);
}

The trick

  Also, what do you think of my self-compiling trick?

//usr/bin/gcc ${0##*/} -o temp && ./temp ; rm temp 2>/dev/null ; exit

Path to compiler hard coded
Compiler hard coded
Deletes a possibly existing file temp without asking

It's a "trick" that's fun to show once, but really don't use it.  If you want to avoid the sequence of commands to compile, run and possibly delete, then write a shell function to do that for you.

Global variable

struct node *head;

You could make your code more general (as in usable for more than one single list instance) if you pass (a pointer to) such a head pointer in to your functions.

Use blocks

    if(curr->next)
        curr->next->prev = curr->prev;

Just always use { /* ... */ }.  Saves you from potential headaches when you later add a line of code without looking too closely.

Consistency

Just some small oddities, nothing of real importance:

You have struct node *next; but also char** argv.  Decide whether you want to keep the * next to the type or the declared name.
You test for (curr != NULL) but also use !curr in a condition later one.  Use either curr != NULL and curr == NULL or curr and !curr.


Validating user's input before creating graph using TChart

Besides deciding if a coefficient is valid or not the function CheckCoefficientBoxesValidInput can also say what is wrong and suggest how the user can fix it.

In order to communicate such information up to the caller and up to the user interface you can use throwing an exception.

Main success scenario would mean no ifs, just sequence of statements.

Exceptional flow would be encoded in try/except blocks, either in this function or somewhere upwards or in the final Application.OnException handler.

Whether the code would be easier to maintain or not is only opinion-based matter of taste and your established coding conventions.

The main improvement would be that the end-user would know what happened and what to do next.

See also:

normative MSDN: Windows → Dev Center - Desktop → Design → Guidelines → Error Messages
informative MSDN: Documentation → Framework Design Guidelines → Design Guidelines for Exceptions


Converting an image from polar to cartesian coordinates

Well for starters, you can use xrange instead of range which will not create an entire list before you iterate, just create values as you need them. You can also move parts of the calculation to upper levels in your loops to decrease the work being done every cycle.

D_pow2 = math.pow(D,2)

for r in xrange(0,1024):
    for phi in xrange(0,90):
        for b in xrange(0,360):
            U = (D + r*sin(b-phi))/D
            l = math.pow(U,-2)

            for s in xrange(0,1024):
                k = D/(math.pow(D_pow2 + math.pow(s,2)),0.5))
                f[r,phi] = 0.5*l*k*q[s,b]*h[s]


Determines whether a number is a power of 2

Both of these ultimately do a linear search trying one power of two after another to see if that one is equal to the input.

Depending on your intent, there's a way that might be better.

A power of two has exactly one bit set, so our job is really to determine whether only one bit is set in the number.

Let's consider a number with only one bit set: 000010000. If we subtract one from this number, we get: 000001111--that is, the least significant 0 bits in the number now become ones, and the least significant bit that was set becomes a 0.

Now, lets see what happens if we do the same to a number with two or more bits set. Let's consider 00010100. If we decrement it, we get 00010011. The same thing has happened--the least significant bit that was set has become a zero, the less significant bits have become one, and any more significant bits remain unchanged.

So, we can define our function as:

def is_power_of_two?(num)
    return num & (num - 1) == 0
end

Sumary

Pros

This has the advantage of being short, simple, and relatively fast.

Cons

It has the disadvantage that although the code is readable, many (especially less experienced programmers) may find the algorithm difficult to understand.


Asynchronous parallel ForEach implemented using Task.Run

Task.WhenAll also accepts Enumerable<Task> as argument. So your lines with tasks can be simplified:

var tasks = source.Select(x => Task.Run(() => body(s), token));
try
{
    await Task.WhenAll(tasks).ConfigureAwait(false);
    token.ThrowIfCancellationRequested();
}
catch
{
    // find the error(s) that might have happened.
    var errors = tasks.Where(tt => tt.IsFaulted).Select(tu => tu.Exception).ToList();

    // we are back in our own thread
    if (errors.Count > 0)
    {
        throw new AggregateException(errors);
    }
}

If you end up throwing because of the line token.ThrowIfCancellationRequested(), after all the tasks have completed (so none of the tasks themselves faulted), I think you end up swallowing the exception.

You provide the CancellationToken to Task.Run. The only thing this does is check whether the token has been cancelled before the tasks starts running. If you want to affect the task itself, you need to pass the token into the method body as well. Additionally, the implementation of body then needs to actually do something with the token (like checking whether it is cancelled), before cancelling will have any use.

So consider the following possible APIs:

Task ForEach<T>(ICollection<T> seq, Func<T, CancellationToken, Task> body, CancellationToken token)

or

Task ForEach<T>(ICollection<T> seq, Func<T, Task> body)

Not much in between will have much use, assuming it's the function body that you want to cancel.

For some additional reading, see here.


Your solution is kind of crappy time complexity wise, as adding elements without removing any takes quadratic time, as you reverse the full stack twice for every value added.  The better algorithm (which I think is amortized constant time) for this problem is to have one stack for input, and another for output. add() simply pushes to the inputStack, while remove() tries to pop from the outputStack, except if it is empty, in which case it first reverses the inputStack onto the outputStack:

public class QueueViaStacks {
    private Stack<Integer> inputStack = new Stack<>();
    private Stack<Integer> outputStack = new Stack<>();

    public void add(int item) {
        inputStack.push(item);
    }

    public int remove() {
        if (outputStack.isEmpty()) {
            while (!inputStack.isEmpty()) {
                outputStack.push(inputStack.pop());
            }
        }
        return outputStack.pop();
    }

    public int size() {
        return inputStack.size() + outputStack.size();
    }
}


Checking if a bag has enough coins in program

1) There's too much duplication. You can define a map, such as:

#This defines a mapping from coin value to a tuple (coin weight, monetary sack value)
coin_types = { 1: (3.56, 1), 2: (7.12, 1), ... }

Then, it's easy to calculate weights and amounts as such:

#This defines a mapping from coin value to a tuple (amount of coins in sack, sack weight)
coins_in_sack_by_type = {k: (v[1] / k, v[1] / k * v[2]) for (k, v) in coin_types.items()}

2) Now, most of your code in the main loop can be collapsed into:

weight_difference = coins_in_sack_by_type[coin_type][1] - sack_weight
coins_changed = weight_difference / coin_types[coin_type][0]


Bash script to determine a distro, update, upgrade and install the apps I use

Simplifying if-elif-else

The else statement here is dead code, it can never happen:

if [ "$close_distro" = "debian" ]; then
  # commands to run if debian
elif [ "$close_distro" != "debian" ]; then
  # commands to run if NOT debian
else
   echo "This is not for you."
fi

The conditions can be simplified to this:

if [ "$close_distro" = debian ]; then
  # commands to run if debian
else
  # commands to run if NOT debian
fi

I also dropped the unnecessary double-quoting around the literal string debian.

Prefer $(...) over `...`

When using sub-shells, instead the obsolete `...`,
always use the modern syntax $(...).

Simplify a chain of commands with awk when possible

In each of these commands, there are 3 processes executed: cat, grep and another grep:

current_distro=`cat /etc/*-release | grep "^ID=" | grep -E -o "[a-z]\w+"`
close_distro=`cat /etc/*-release | grep "^ID_LIKE=" | grep -E -o "[a-z]\w+"`

You can make that more efficient by rewriting each using a single awk:

current_distro=$(awk -F= '$1 == "ID" { print $2 }' /etc/*-release)
close_distro=$(awk -F= '$1 == "ID_LIKE" { print $2 }' /etc/*-release)


Custom exception for string that is too long

if(str1.equalsIgnoreCase("done"))
        System.exit(0); //exit on first startup

Do not use System.exit() (somewhere else then in a catch block in main) It terminates the JVM immediately. This is usually not intended.
just write a return instead.

         if(str1.length()>MAX_STRING_LENGTH)
                throw new StringTooLongException();
            System.out.println("\nEnter a string, enter DONE when finished:\n");
            str1 = input.nextLine();

This will result in an endless loop when the user enters a long string. The check is done (and the exception thrown) before she gets a chance to enter a new one.

You should move the if behind the input request and delete the initial input request (along wit the if there) before the loop.

Since you do nothing else in the loop the checking the string and requesting new one some may argue that you use the Exception as flow control for which exceptions are not supposed to be used.
I'd agree to that argument in this particular case as long as the "happy path" also repeats the loop...


Drop-down menu button highlighting and hiding

There is no reason to swap the text, find the span in the button and toggle the class

var isDefault = parentBtn.hasClass('defaultbutton')
$(this).parents('.dropdowncontain').find('.button .caret').toggleClass("invert", isDefault);

The context selector is a bad idea

$('.dropdown-menu', this)

It is slow. Use find()

$(this).find('.dropdown-menu')

Another thing, $(this) is used over and over again. That is bad practice. It creates a new jQuery object each time. Store it in a variable and reuse that variable.

var myElement = $(this);
myElement.find('.dropdown-menu')...


Modified Fibonacci method implementation - dynamic programming

Making the array initialization better:

t1,t2,n = map(int, raw_input().split(" "))
array = [t1, t2]
for i in range(2,n):
   ele = array[i-2] + array[i-1]*array[i-1]
   array.append(ele)
print array[n-1]

Currently your code needs \$\mathcal{O}(n)\$ memory, because you keep all terms. It would be more efficient to just save \$t_{n-1}\$ and \$t_{n-2}\$ and update them every loop, using tuple assignment:

t1, t2, n = map(int, raw_input().split())
for _ in range(2, n):
   t1, t2 = t2 + t1**2, t1
print t2 + t1**2


Generic EventArgs to go with generic EventHandler?

You could make it a little bit more useful if you added some supporting factory methods to create the arguments.  That way you don't have to use the constructor and its somewhat awkward syntax (having to supply the types).

public static class EventHandlerExtensions
{
    public static EventArgs<T> CreateArgs<T>(
        this EventHandler<EventArgs<T>> _,
        T argument)
    {
        return new EventArgs<T>(argument);
    }

    public static ReadOnlyEventArgs<T> CreateArgs<T>(
        this EventHandler<ReadOnlyEventArgs<T>> _,
        T argument)
    {
        return new ReadOnlyEventArgs<T>(argument);
    }
}

Then to create the instance of the arguments, you could just do this:

public event EventHandler<EventArgs<SomeArg>> SomeEvent;
public event EventHandler<ReadOnlyEventArgs<SomeArg>> SomeOtherEvent;

protected virtual void OnSomeEvent(SomeArg argument)
{
    var someEvent = SomeEvent;
    if (someEvent != null)
    {
        var args = someEvent.CreateArgs(argument);
        // instead of:
        //var args = new EventArgs<SomeArg>(argument);
        someEvent(this, args);
    }
}

protected virtual void OnSomeOtherEvent(SomeArg argument)
{
    var someOtherEvent = SomeOtherEvent;
    if (someOtherEvent != null)
    {
        var args = someOtherEvent.CreateArgs(argument);
        // instead of:
        //var args = new ReadOnlyEventArgs<SomeArg>(argument);
        someOtherEvent(this, args);
    }
}

It might be useful to have options for multiple parameters (similar to how the tuple is).  Though it might not be feasible to have all combinations of multiple (im)mutable arguments.


DTO interfaces for implementing web service integration

I am not sure I understand what's the reason of your Dto and of its AbstractDto and DtoImpl implementations. Why does it need to hold a dtoData instance?
I think that you should separate the definition of Dtos, the definition of DtoData and the definition of a Mapper that translates between the two representation.

I think you should't really have a Dto interface or leave it to be just a marker interface, but I don't really like them as they are usually an anti pattern.

I don't like that you pass directly a Map to your DtoData. What about something implementing this (very Map-like) interface?

interface DtoData
{
    void setValue(String key, object value);
    void getValue(String key, object value);
    Set<String> getKeys();
}

Finally all the conversions should be handled by a Mapper, implementing this interface.

inteface Mapper
{
    Object toDto(DtoData dtoData);
    DtoData toDtoData(Object dto);
}

If you organise your program in this way you have different pieces that cover different responsibilities and it should be trival to change format of DtoData and the way you map them.

One possible improvement over that would be to let the compiler help you putting everything together in the right way. You can do that by rewriting Mapper such that it is generic. Something like Mapper<T,K>.


finding boundary elements in cartesian grid

Headers

I had to ditch the non-standard and missing "stdafx.h", add <algorithm> and fix the spelling of <iostream> to compile this.

Correct std::size_t

This type is consistently written as size_t without its namespace prefix, which is not portable.

Cell type

struct cell could simply be a std::pair, but there may be benefit to stronger typing as you have it.  I recommend you prefer initialization of members rather than assignment (and that conveniently allows us to simply omit the constructor).  We can also change the == operator to take a reference and make it const (we could lean on std::tuple for the implementation, but it doesn't seem worth it for two members and only one operator).

struct cell
{
    const std::size_t x;
    const std::size_t y;

    bool operator==(const cell& a) const { return a.x == x && a.y == y; }
};

Algorithm

Repeatedly searching for elements looks like a very time-consuming way of examining every cell.  Instead, we could just iterate over the known cells and update a set of minima and maxima for its row and column:

#include <iostream>
#include <map>
#include <set>
#include <utility>
#include <vector>

struct cell
{
    const std::size_t x;
    const std::size_t y;
};

int main()
{
    std::vector<cell> cartesian = {
        {0, 1}, {0, 2}, {0, 3},
        {1, 2}, {1, 3}, {1, 4}, {1, 5},
        {2, 1}, {2, 2}, {2, 3}, {2, 4}, {2, 5},
        {3, 0}, {3, 1}, {3, 2}, {3, 3}, {3, 4}, {3, 5}, {3, 6},
        {4, 2}, {4, 3}, {4, 4}, {4, 5}, {4, 6}
    };

    // map each row and column to (min,max) filled cell in that column
    std::map<std::size_t, std::pair<std::size_t,std::size_t>> row_range;
    std::map<std::size_t, std::pair<std::size_t,std::size_t>> column_range;

    for (const auto& c: cartesian) {
        auto rit = row_range.find(c.y);
        if (rit != row_range.end()) {
            auto& row = rit->second;
            if (c.x < row.first) {
                row.first = c.x;
            } else if (row.second < c.x) {
                row.second = c.x;
            }
        } else {
            row_range.insert({c.y, {c.x, c.x}});
        }

        auto cit = column_range.find(c.x);
        if (cit != column_range.end()) {
            auto& col = cit->second;
            if (c.y < col.first) {
                col.first = c.y;
            } else if (col.second < c.y) {
                col.second = c.y;
            }
        } else {
            column_range.insert({c.x, {c.y, c.y}});
        }
    }

    // show the results for column 0
    const auto zr = column_range[0];

    std::cout  << zr.first << ',' << zr.second << std::endl;
}

We can refactor the part that's common to rows and columns into a small helper method:

using range_map = std::map<std::size_t, std::pair<std::size_t,std::size_t>>;

static void update_min_max(range_map& ranges, std::size_t index,
                           std::size_t value)
{
    auto it = ranges.find(index);
    if (it != ranges.end()) {
        auto& range = it->second;
        if (value < range.first) {
            range.first = value;
        } else if (range.second < value) {
            range.second = value;
        }
    } else {
        ranges.insert({index, {value, value}});
    }
}

And then the loop becomes

    range_map row_range;
    range_map column_range;

    for (const auto& c: cartesian) {
        update_min_max(row_range, c.y, c.x);
        update_min_max(column_range, c.x, c.y);
    }


Here are a few considerations.

DEFPARAMETER vs. DEFVAR

The first three definitions should be given with defparameter instead of defvar. The first operator is used for values that do not change, unless they are modified in the source file and then recompiled. The second for variables that can be modified at run time but, when reloaded and recompiled, does not modify the current run-time value (i.e. are not re-initialized).

Comparison operators on more than one value

In Common Lisp is very handy the possibility of using all the comparison operators with more then one argument. For instance if you want to check if the numbers a, b and c are all equal, you can simply write (= a b c); if you want to check that they are all different among them (that is that the are no two values equal), you can write (\= a b c). This can simplify the function is-move-free as well as make non necessary the function is-same.

Semplification of the win functions

In effect they have all the same pattern: you compare three value starting with a certain index and then incrementing that index with the same value two times. For this reason I suggest a more simple function that includes all the three:

(defun win (board)
  (flet ((check (start increment)
                (= (elt board start) (elt board (incf start increment)) (elt board (incf start increment)))))
    (some #'check '(0 3 6 0 1 2 0 2) '(1 1 1 3 3 3 4 2))))

Note:

The use of the flet to define an internal function: defun should be used only for top level functions. In case of internal recursive functions you should use labels instead of flet.
The use of incf which performs a side-effect incrementing the value of a variable (which is safe in this case since in Common Lisp parameters are passed by value).
The use of some which is a functional that returns a true value if some predicate is at least once true when applied to one (or more) lists. In this case the predicate is check and it is applied to the list of starting indexes, and the list of the increments.

The final code

Here is the entire code with my modifications:

(defparameter p1 88) ; char code for 'X'
(defparameter p2 79) ; char code for 'O'
(defparameter tie 49) ; arbitrary constant to represent ties

(defun is-move-free (move board)
  (let ((player (elt board move)))
    (/= p1 p2 player)))

(defun win (board)
  (flet ((check (start increment)
                (= (elt board start) (elt board (incf start increment)) (elt board (incf start increment)))))
    (some #'check '(0 3 6 0 1 2 0 2) '(1 1 1 3 3 3 4 2))))

;;; This function gets the players move, plays it if possible
;;; then gets the next move. The game will play out in it's
;;; entirety through recursively calling this function.
(defun get-player-move (player board move-num)
  (apply #'format t " ~C | ~C | ~C ~%-----------~% ~C | ~C | ~C ~%-----------~% ~C | ~C | ~C~%" (mapcar #'code-char board)) ; Print the board
  (if (>= move-num 9) ; if all the moves have been played, and there is no winner
      tie               ; return the tie constant
      (let ((move (- (parse-integer (read-line)) 1))) ; get the move from input, and convert it to list location
        (if (is-move-free move board)
            (let ((board (substitute player (elt board move) board))) ; apply the move, and get the new board
              (if (win board) ; check if this was the winning move
                  (elt board move) ; return the winner
                  (get-player-move (if (= player p1) p2 p1) board (+ move-num 1)))) ; continue the game
            (get-player-move player board move-num))))) ; move again, if the move was taken

(let ((result (get-player-move p1 '(49 50 51 52 53 54 55 56 57) 0)))
  (if (= result tie)
      (format t "It's a tie!")
      (format t "The winner is ~C" (code-char result))))

Note the use of the more common indentention convention for the if, as well as the semplification of the format.

An iterative version

Common Lisp has been designed to be used both with applicative (i.e. functional) style, as well as imperative (i.e. with side-effect) style. So, instead of using the applicative style of creating each time a new board with substitute and passing it to a recursive call of the function get-player-move, an alternative could be a simple iterative style, like for instance:

(defun get-player-move (player board move-num)
  (loop
    (apply #'format t " ~C | ~C | ~C ~%-----------~% ~C | ~C | ~C ~%-----------~% ~C | ~C | ~C~%" (mapcar #'code-char board)) ; Print the board
    (let ((move (- (parse-integer (read-line)) 1)))
      (when (is-move-free move board)
        (setf (elt board move) player)
        (when (win board) (return player))
        (incf move-num)
        (when (= move-num 9) (return tie))
        (setf player (if (= player p1) p2 p1))))))

Note that in this case, since the board is modified, one should create it initially with (list 49 50 51 52 53 54 55 56 57), instead of using a constant like '(49 50 51 52 53 54 55 56 57).


First of all, you should be using return rather than print to get a value out of a function, otherwise you'll have problems when you try to expand the program.

def mac_conv(mac, sep='-'):

  #etc

  #return final MAC address
  return final_mac

#Open file with MAC addresses and convert them
with open('mac.txt', 'r') as f:
  for mac in f.readlines():
    print(mac_conv(mac))

I would also avoid reusing variables, especially if its a function argument (mac).  You can actually eliminate that usage of the variable all together:

#join groups into a single MAC
final_mac = '.'.join([gr1, gr2, gr3])

If I was writing this, however, I would probably do it in just a couple of lines, as you know exactly how the input and output strings are going to be formatted:

def mac_conv(mac, sep='-'):
    mac_parts = mac.split(sep)
    return "{0[0]}{0[1]}.{0[2]}{0[3]}.{0[4]}{0[5]}".format(mac_parts)

If this was going into a product, I would probably add some error handling too, to allow for input that isn't a mac address - too short, too long, wrong separators, alternate groupings (a cisco-formatted address is still a valid mac address, but this function won't handle it.)


Checking a Model's function's return value and setting values to a View member

Don't call List<T> "somethingList" -- e.g. if they are questions, call it questions, not questionList.

Why do you do List<List<string>> questionList = new List<List<string>>(); if the next step is questionList = _model.GetQuestions();? Instead don't bother with the initialization and just assign it directly: var questionList = _model.GetQuestions();

List<List<string>> is a warning sign to me that your design is probably flawed, and when I look at the context -- a list of questions and a separate list of answers -- I fear that your code has far worse issues than the reason for this question.

Is there a reason you're doing this in an "outdated" technology like WinForms when WPF etc. exists? There is a strong link between data and UI in this method, which is a frequent issue with WinForms; if this was WPF you could implement MVVM to separate those concerns.


Vector v is not required.  Instead of adding items to it, iterate directly over your source array, and then use variance = E(v²) / E(v)² so that your inner code becomes:

        double sum = 0;
        int n = kernelSize * kernelSize;
        // Kernel Patch
        for (int kx = ...) {
            for (int ky = ...) {
                double d = (double)input[img.step * kx + ky]);
                sum += d;
            }
        }
        const double mean = sum/n;

        double sum2 = 0;
        for (int kx = ...) {
            for (int ky = ...) {
                double d = (double)input[img.step * kx + ky]);
                sum2 += (d - mean) * (d - mean);
            }
        }
        const double stddev = sqrt(sum2/n);
        if (stddev < threshold) {
            ...;
        }

After that, consider that the sum of elements centred around (x+1,y) can be found from the result for (x,y) simply by subtracting all the elements in the previous left-hand column, and adding all the elements in the new right-hand column.  An analogous operation works vertically.

Also, check your compiler options - are you auto-vectorizing loops, and using SIMD instructions (if available)?