Check for boolean values in an object and convert them to numbers

Before I do anything else I feel compelled to clean up your spacing convert " to ' to consistantly use only one type of strings

var obj = {
    'label': 'test',
    'tel': 123456,
    'settings': {
        'playback': false,
        'attachfile': true,
    },
    'setTime': true,
    'setDay': false,
    'arrSettings': [
        'Testing',
        {'playback': false, 'attachfile': true},
        {'playback': false, 'attachfile': true},
        123456789
    ]
};

function changeBooleanToNumber(o) {
    for (var key in o) {
        if (/^boolean$/i.test(typeof o[key])) {
            o[key] = Number(o[key]);
        }

        if (Object.prototype.toString.call(o[key]) === '[object Object]') {
            changeBooleanToNumber(o[key]);
        } else if (Object.prototype.toString.call(o[key]) === '[object Array]') {
            for (var i = 0; i < o[key].length - 1; i++) {
                if(Object.prototype.toString.call(o[key][i]) === '[object Object]') {
                    changeBooleanToNumber(o[key]);
                }
            }
        }
    }
}

changeBooleanToNumber(obj);

Now:

Use +x instead of Number(x); it is shorter and faster in all cases I've ever bothered to test.
Don't use var inline, javascript doesn't have block scope (only function scope) so it is better to declare all necessary variables at the start of your functions.
Cache Object.prototype.toString to make code more readable.
Use toString instead of a regex test for checking for the bool type
simplify for loop and store the upper bound in a variable instead of computing it every time
Use a hasOwnProperty check on the for in loop.

This leaves me with this:

function changeBooleanToNumber(o) {
    var toString = {}.toString,
        hasOwn = {}.hasOwnProperty,
        key,
        i,
        len;
    for (key in o) {
        if (hasOwn.call(o,key)) {
            if (toString.call(o[key]) === '[object Boolean]') {
                o[key] = +o[key];
            } else if (toString.call(o[key]) === '[object Object]') {
                changeBooleanToNumber(o[key]);
            } else if (toString.call(o[key]) === '[object Array]') {
                len = o[key].length;
                for (i = 0; i < len; i++) {
                    if(toString.call(o[key][i]) === '[object Object]') {
                        changeBooleanToNumber(o[key]);
                    }
                }
            }
        }
    }
}

This resulting code looks to me like it has too many indents. I also notice that it fails on passing in an object that is an array or contains an array of arrays. Reordering some code we can check both of those cases at the root level:

function changeBooleanToNumber(o) {
    var toString = {}.toString,
        hasOwn = {}.hasOwnProperty,
        key,
        len;
    if (toString.call(o) === '[object Object]') {
        for (key in o) {
            if (hasOwn.call(o, key)) {
                if (toString.call(o[key]) === '[object Boolean]') {
                    o[key] = +o[key];
                } else if (toString.call(o[key]) === '[object Object]') {
                    changeBooleanToNumber(o[key]);
                } else if (toString.call(o[key]) === '[object Array]') {
                    changeBooleanToNumber(o[key]);
                }
            }
        }
    } else if (toString.call(o) === '[object Array]') {
        len = o.length;
        for (key = 0; key < len; key++) {
            if (toString.call(o[key]) === '[object Boolean]') {
                o[key] = +o[key];
            } else if (toString.call(o[key]) === '[object Object]') {
                changeBooleanToNumber(o[key]);
            } else if (toString.call(o[key]) === '[object Array]') {
                changeBooleanToNumber(o[key]);
            }
        }
    }
}

However now there is a bunch of duplicate code. This can be reduced by abstracting a function:

function changeBooleanToNumberHelper(o, key) {
    var toString = {}.toString;
    if (toString.call(o[key]) === '[object Boolean]') {
        o[key] = +o[key];
    } else if (toString.call(o[key]) === '[object Object]') {
        changeBooleanToNumber(o[key]);
    } else if (toString.call(o[key]) === '[object Array]') {
        changeBooleanToNumber(o[key]);
    }
}
function changeBooleanToNumber(o) {
    var toString = {}.toString,
        hasOwn = {}.hasOwnProperty,
        key,
        len;
    if (toString.call(o) === '[object Object]') {
        for (key in o) {
            if (hasOwn.call(o, key)) {
                changeBooleanToNumberHelper(o, key);
            }
        }
    } else if (toString.call(o) === '[object Array]') {
        len = o.length;
        for (key = 0; key < len; key++) {
            changeBooleanToNumberHelper(o, key);
        }
    }
}

Here, the if statements look very similar. It turns out we can inline this helper function:

function changeBooleanToNumber(o, key) {
    var toString = {}.toString,
        hasOwn = {}.hasOwnProperty,
        len;
    if (key) {
        if (toString.call(o[key]) === '[object Boolean]') {
            o[key] = +o[key];
            return;
        }
        o = o[key];
    }
    if (toString.call(o) === '[object Object]') {
        for (key in o) {
            if (hasOwn.call(o, key)) {
                changeBooleanToNumber(o, key);
            }
        }
    } else if (toString.call(o) === '[object Array]') {
        len = o.length;
        for (key = 0; key < len; key++) {
            changeBooleanToNumber(o, key);
        }
    }
}

Without going farther I recognize this pattern as a depth first graph traversal with a little additional functionality. I would abstract that a little and see this helper function:

function depthVisit(node, visit, key) {
    var toString = {}.toString,
        hasOwn = {}.hasOwnProperty,
        len;
    if (key) {
        if (visit(node, key) === false) {
            return;
        }
        node = node[key];
    }
    if (toString.call(node) === '[object Object]') {
        for (key in node) {
            if (hasOwn.call(node, key)) {
                depthVisit(node, visit, key);
            }
        }
    } else if (toString.call(node) === '[object Array]') {
        len = node.length;
        for (key = 0; key < len; key++) {
            depthVisit(node, visit, key);
        }
    }
}

function changeBooleanToNumber(o) {
    depthVisit(o, function (parent, key) {
        if ({}.toString.call(parent[key]) === '[object Boolean]') {
            parent[key] = +parent[key];
        }
    });
}

However I know this function has a bug: javascript can have cyclic references (causing infinite recursion). To fix that I need to either limit the traversal to a particular depth or check if I have already visited an object. Here I'll do the latter:

function depthVisit(node, visit) {
    var set = [];
    function seen(node) {
        var i = set.length - 1;
        while (set[i] !== node && i > 0) { i--; }
        set.push(node);
        return i !== -1 && set[i] === node;
    }
    function inner(node, key) {
        var toString = {}.toString,
            hasOwn = {}.hasOwnProperty,
            len;
        if (key) {
            if (visit(node, key) === false) {
                return;
            }
            node = node[key];
        }
        if (seen(node)) {
            return;
        }
        if (toString.call(node) === '[object Object]') {
            for (key in node) {
                if (hasOwn.call(node, key)) {
                    inner(node, key);
                }
            }
        } else if (toString.call(node) === '[object Array]') {
            len = node.length;
            for (key = 0; key < len; key++) {
                inner(node, key);
            }
        }
    }
    inner(node);
}

function changeBooleanToNumber2(o) {
    depthVisit(o, function (parent, key) {
        if ({}.toString.call(parent[key]) === '[object Boolean]') {
            parent[key] = +parent[key];
        }
    });
}

JsFiddle to show it works.

Interestingly this version is also about 20% faster than the original code. (see: http://jsperf.com/graph-traversal)


applicationDidBecomeActive: Am I causing a memory leak?

This code doesn't appear to leak. To be sure, however, you should use the leaks instrument to periodically check your code.

To do such,

Select Product -> Profile (or, ⌘ I)
Choose `Leaks`
Select Profile
Exercise your app (i.e. go through all the options, background it, etc)

For more information on using the leaks tool, you can checkout Ray Wenderlich's Instruments Tutorial for iOS: How to Debug Memory Leaks.

Additional Notes:

1) Unless you have a really good reason to, you shouldn't be setting self.window.rootViewController every time that the app returns to the foreground. Instead of calling showMainWindow from within applicationDidBecomeActive, you should probably move this code within application:didFinishLaunchingWithOptions:, which is the more common place to do  initial app setup.

Further, if you need a controller to know when the app has entered the foreground (I imagine that this is the reason you're actually doing this), you should have it register to receive notification of UIApplicationWillEnterForegroundNotification. I.e.

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(YOUR_SELECTOR)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];

    // ... whatever else you do here...
}

// Also make sure to unregister too
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

2) To make this code a bit more cleaner and easier to read, I would rewrite it like this:

- (void)showMainWindow
{

    NSLog(@"@Info @AppDelegate: Showing Main Window");

    self.leftMenuViewController = [[MenuViewController alloc]initWithSide:@"left"];;
    self.rightMenuViewController = [[MenuViewController alloc]initWithSide:@"right"];;

    self.viewDeckController =  [[IIViewDeckController alloc] initWithCenterViewController:self.webViewController
                                                                                leftViewController:self.leftMenuViewController
                                                                           rightViewController:self.rightMenuViewController];

  self.window.rootViewController = self.viewDeckController;
  [[NSNotificationCenter defaultCenter] postNotificationName:@"updateNavigationBar" object:nil];
}

In such, you don't have to explicitly set self.leftMenuViewController and self.rightMenuViewController to nil or create the temp objects.


Extracting lines from a file, the smelly way

Yes, it is indeed a bit sketchy/confusing to use takewhile when you really don't want to take the lines, but discard them. I think it's better to use dropwhile and then use its return value instead of discarding it. I believe that that captures the intent much more clearly:

def extractEventLog(fh):
    fhlines = (x.strip() for x in fh)
    lines = itertools.dropwhile(lambda x: 'Event Log' not in x, fhlines)
    lines = itertools.dropwhile(lambda x: '-----' not in x, lines)
    lines.next() # Drop the line with the dashes
    lines = itertools.takewhile(len, lines) # Event log terminated by blank line
    for line in lines:
        yield line # In the real code, it's parseEventLogLine(line)


Update

@steenslag points out the minmax builtin. No monkey patching necessary.

template_min_datestamp, template_max_datestamp = Template.range(:created_at).minmax


Speed up weighted average for Leela Chess Zero

Possible improvements:

Calculate for less than 40 variables. Take top 5 and calculate the probabilities for them. The Monte-Carlo shows that the probabilities go down fast. And reducing the number of variables will significantly reduce complexity.
Only take variables that are 2 standard deviations from the maximum
In Monte-Carlo you spend 83% time in generating normally distributed random variables. Check lagged Fibonacci generator. Link
Monte-Carlo numpy calculations could all be combined into one loop in a lower level language (numba, C++, C).
Use pairwise probabilities of all variables with maximum variable to approximate the probabilities.

Code for profiling Monte-Carlo:

%load_ext line_profiler
%lprun -f monte monte()

Output:

Timer unit: 3.52617e-07 s

Total time: 0.0399899 s
File: <ipython-input-2-5df66cc29248>
Function: monte at line 1

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           def monte():
     2         1         20.0     20.0      0.0      nn=10000
     3         1      94115.0  94115.0     83.0      a = np.random.normal(size=(len(m),nn))*sd[:,None]+m[:,None]
     4         1      19254.0  19254.0     17.0      vals = (a==a.max(axis=0)).sum(axis=1)/nn
     5         1         19.0     19.0      0.0      vals *= m
     6         1          1.0      1.0      0.0      return vals


One suggestion is to simplify your top-level function by taking
advantage of a library and using a data structure to eliminate conditional logic.
import pathlib

def wordcounter(file_path):
    # Let a built-in library solve this problem.
    extension = pathlib.Path(file_path).suffix

    # Hold the counter functions in a data structure.
    # You'll need to create a couple of these.
    counters = {
        'xlsx': excel_counter,
        'docx': word_counter,
        'txt': txt_counter,
        'pdf': pdf_counter,
    }

    # Then just do what you want directly rather than checking conditions.
    return counters[extension](file_path)

Another observation is that your counter functions are duplicating the word
counting logic. Such duplication is often a signal that there are refactoring
possibilities: more specifically, the thing being duplicated might belong in
its own function. If we do that, you'll need to convert your current counter
functions (which take a path and return an integer) into reader functions (take a path
and yield chunks of text). Such a refactor is illustrated for excel_reader.
And those changes will imply a few simple adjustments in wordcounter.
def count_words(reader, file_path):
    n = 0
    for text in reader(file_path):
        n += len(text.split())
    return n

def excel_reader(file_path):
    wb = openpyxl.load_workbook(filename)
    for sheet in wb:
        for row in sheet:
            for cell in row:
                # Your current logic.
                text = str(cell.value)
                if text != "None":
                    yield text

                # I've never used openpxl, but a quick internet
                # search suggests that this is more robust conditional
                # check to filter out empty cells.
                if cell.value is not None:
                    yield str(cell.value)


In general, you shouldn't expose synchronous operations as asynchronous, see Should I expose asynchronous wrappers for synchronous methods? If a method doesn't have an async version, just expose it synchronously. The caller can then choose to run it on another thread, if that makes sense.


Determine if all characters are unique in string: Without using Bitwise operator

The time complexity of both solutions is linear, proportional to the length of the input.

The space complexity of the solution in the book is constant, it uses a single integer regardless of the length of the input.

The space complexity of your solution is linear, it uses extra storage proportional to the size of the input. This is largely due to the str.toCharArray() call, which will result in an array the same size as the length of the input.

You could remedy that, by changing to a counting loop and using .charAt to access the characters. With that simple change, your space complexity becomes constant too, due to the finite size of the alphabet. However, you will still use more space than the book's solution, due to the set.

Your solution has several pretty grave mistakes:

printing instead of functions returning values
using an int with values 0 and 1 instead of a proper boolean
using a flag variable, when it's not necessary at all
strange, non-standard formatting


First go at my own form validation, and suggestions?

A couple of small changes:

near the end:

if (errors == true) {
    return false;
}
else {
    var errors = false;
    alert("Submitted");
    return true;
}

Could be:

if(!errors)
{
    alert("Submitted");
}
return !errors;

the .req

if($(this).val() == ''){

could be:

if(!$(this).val()){

This would actually be a problem because

 " " != ""

so a space would validate (if that's what you intended then ignore this one ;) )
var errors= false; needs to be inside the click event:

 $('.submit').click(function() {
     var errors = false;

otherwise when you click the submit a second time after an invalid attempt it won't reset the value.

Alternatively:-

http://jsfiddle.net/ssTPm/

var validationConfig = [
{
    "selector": ".req",
    "hasErrors": function() {
        return !$(this).val()
    },
    "errorMessage": "Required field."},
{
    "selector": '.reqe',
    "hasErrors": function() {
        return $('.reqe').val().indexOf('@') === -1
    },
    "errorMessage": "Please enter valid email."
}];

then a nice loop like:

for (var i = 0, validation = null; validation = validationConfig[i]; i++) {
    $(validation.selector).each(validateEach);
}

and validateEach would look like:

 function validateEach () {
    var hasErrors = validation.hasErrors.call(this);
    errors |= hasErrors;
    if (hasErrors) {
        $(this).after(validation.errorMessage);
    }
};

This would mean you could have the validation function in you js files and then when you initialise the page from the server you just output the validationConfig:

validationConfig = validationConfig || [];
validationConfig.concat([
    {
        "selector": ...
    }
];

as many times as you like. Although from the looks of things it might be over-engineering things a bit.

Explanations:-

so the || is a coalesce or OR operator.

myVariable = myVariable || [];

means if myVariable results in a true value (not false, undefined, null etc etc) then it does nothing otherwise it assigns it a defualt value.

so if I had the following:

myList = myList|| [];
myList.push(1);
myList = myList|| [];
myList.push(2);
myList = myList|| [];
myList.push(3);

it would result in [1,2,3]. The first time it sets the value as [] the next times they just assign itself to itself. This way it doesn't need to know if it has been initialised or not.

the |= is a bitwise | (BITWISE OR) and an = so

value |= otherValue;

is the equivalent to

value = value | otherValue;

In this example

errors |= hasErrors;

is the exact same as

errors = errors || hasErrors;

Errors is assigned true as long as either it was already true or hasErrors is true;


There are a few things I see:

Work in the constructor - Don't do work in the constructor. Ideally the only things that should be in the constructor are assignments.
DRY - Why are you repeating $this->start() all over the place?
What's up with that destroy() method? You're doing stuff there other than destroying the session! Why?
Your session_start() should happen once, in the constructor.
It would be more flexible if you passed the $_SESSION array as a parameter in the constructor, rather than relying on globals.


A lot of what you are doing is repeated code so you should DRY it out.  For instance, widthPerc is the same code except for the values of widthTop and widthBottom. We can also simply all of our checks by setting them up as vars.  So that could be re-written like this:

var isFirstTwo = !!( i < 3 ); // go ahead and just eval once
var isEven = !!( i % 2 ); // go ahead and just evalonce

//which width value do we want?
var widthDir = ( isFirstTwo ) ? widthTop : widthBottom;
//is it an even number?
widthDir = ( isEven ) ? widthDir : 100 - widthDir;
widthBlock = widthDir * widthBlock / 100;

divisionObj.widthPerc = widthDir +'%';
divisionObj.width = widthBlock;

This reduces a lot of your code.  You could follow a similar technique for height (it's actually easier than width).

var heightTop = ( isEven ) ? heightTop : (100 - heightTop);
var heightBlock =  heightBlock * heightTop / 100
divisionObj.heightPerc = heightTop + '%';
divisionObj.height = heightBlock;

Hope that helps. I have updated the fiddle. Let me know if you have questions or comments.


Some notes on your coding style:

Why do you do int resultForSkip = page * recordsPerPage; at the start of GetTodayTasks? You never use this variable.
var _result = new List<Schedule>();: the underscore prefix should be used to indicate class-level fields, not variables inside a method. Why even call it _result, when schedules is far more clear?
data is also way too generic as a name.
GetExpression doesn't return an expression.
Why is the parameter of Calculate(List<Schedule> schedules) a List<T>? An IEnumerable<T> suffices.
Don't abbreviate "do not" to "don't" in variable names: dontContinue.
The "Falg" in timeFalg should be "Flag".
countersuccessTriggers is improperly capitalized, but it's also badly named. Perhaps successTriggerCount would be better.
There are several places where random blank lines appear. Please clean these.
Use descriptive names: foreach (var item in schedule.Triggers). Why call it an item when it is a trigger?
Why is the property called TypeId? Judging from the rest of the code it is an enum value, so why not call it Type?
Method scope variables should be camelCase, so IsAllTriggersRequired, AllTriggersAvailabe, AnyTriggersAvailabe are incorrect.
Also pay attention to verb conjugations: IsAllTriggersRequired should be areAllTriggersRequired.
However, looking at IsAllTriggersRequired, AllTriggersAvailabe and AnyTriggersAvailabe there are more problems beyond those already mentioned: the naming is inconsistent and feels incorrect. Boolean names like "IsAvailabe" are great as property names, but don't work well as variable names. In this case I'd go for allTriggersAreRequired, allTriggersAreAvailabe and anyTriggerIsAvailabe.


Because every filename can have side effects, they are stored in string option types.

I don't understand what you mean by that, but it's not particularly important for the rest of the question.

Your concern about the structure of the code is valid. Fortunately, you have several options. Let's start gently.

Map3

Option.map is useful if you have a single option value, and you want to transform it into another option value if the input value is a Some case. If you have two option values, you'll need a hypothetical Option.map2 function, and in this case, where you have three option values, you'll need a hypothetical Option.map3 function. These functions are not yet available in the Option module, but are being considered for inclusion in the future.

You can easily write the required function yourself, though:

// ('a -> 'b -> 'c -> 'd) -> 'a option -> 'b option -> 'c option -> 'd option
let optionMap3 f x y z =
    match x, y, z with
    | Some x', Some y', Some z' -> f x' y' z' |> Some
    | _ -> None

This completely generic function would enable you to write an option-based function adapter over your nice toHtmlNoOption function:

let toHtml' (sc : HtmlTransformer) =
    let xfn = sc.XslFile |> Option.map (fun (XslFile xf)  -> xf)
    let xmlFn = sc.XmlFile |> Option.map (fun (XmlFile xf)  -> xf)
    let htmlFn = sc.HtmlPage|> Option.map (fun (HtmlPage lp) -> lp)

    (xfn, xmlFn, htmlFn) |||> optionMap3 toHtmlNoOption

The return expression uses the exotic |||> pipe operator to compose the three option values into toHtmlNoOption, which will only be invoked if all three values are Some cases.

Computation expression

You can do better, though, using a computation expression. There's no built-in computation expression for option types, but you can easily add a minimal one that addresses this particular purpose:

type OptionBuilder () =
    member this.Bind(v, f) = Option.bind f v
    member this.Return v = Some v

let option = OptionBuilder ()

This enables you to rewrite the function like this:

let toHtml'' (sc : HtmlTransformer) = option {
    let! XslFile xfn = sc.XslFile
    let! XmlFile xmlFn = sc.XmlFile
    let! HtmlPage htmlFn = sc.HtmlPage

    return toHtmlNoOption xfn xmlFn htmlFn }

Notice how the use of let!-bound values enable you to use pattern matching to destructure the string values out of the single-union cases. Within this option expression, xfn, xmlFn, and htmlFn all have the type string.

Because this expression is evaluated within an option computation expression, it'll short-circuit and return None as soon as any of the let!-bound values turn out to be None. Only if they are all Some cases does it evaluate all the way to the end, where it calls into the toHtmlNoOption function and returns the return value of that function call.


Calculates best angle on path and approximates cardinal direction

Two suggestions:

in the cardinal function, return the number rather than setting a variable, so you shortcut all the other if statements. You could further optimize that by doing a binary rather than a linear search.
your direction function could be replaced by an array: int directions[8] = {"north", "northeast", ... };. Then the lookup is simply directions[cardinal]


A 'slow sort': repeatedly swap the first misordered pair

There are a few terms one can use to grade code. Correctness, efficiency, readabilty, reuse testability and few other objectively measurable metrics come to mind.

Efficiency isn't really a concern here, and due to the simplicity of the algorithm, neither is correctness. However, it was hard to check whether the code is correct because it's nearly not readable. Also, it's not reusable, at all, as the sorting method is embedded inline and therefore not testable.

With this small overview in mind, let's review the code in detail.

Correctness

The outer while loop will only exit when srcPos == arrLen - 1. This may only happen if srcPos does not get set to 0, which again only happens if two elements weren't in order. Therefore when we have srcPos == arrLen - 1, all elements where lesser or equal to their predecessors and the array is sorted.

Efficiency

This was an inverse goal. While it's already slow, I accidentally misread the code (see the next section) and read:

...
   var srcPos=0,dstPos,tmp; // declare variables
   while (srcPos<arrLen-1) {
        dstPos=srcPos+1;
        while (dstPos<arrLen) { // three swap routines
             if (arr[srcPos]>arr[dstPos]) {tmp=arr[srcPos];arr[srcPos]=arr[dstPos];arr[dstPos]=tmp;srcPos=0;break}
             //if (arr[srcPos]>arr[dstPos]) {arr[srcPos]^=arr[dstPos];arr[dstPos]^=arr[srcPos];arr[srcPos]^=arr[dstPos];srcPos=0;break}
             //if (arr[srcPos]>arr[dstPos]) {arr[srcPos]+=arr[dstPos];arr[dstPos]=arr[srcPos]-arr[srcPos];arr[srcPos]+=arr[dstPos];srcPos=0;break}

             dstPos++;
             }
             srcPos++; // whoops!
       }
 ...

That's even worse, since we end up with a lot of unnecessary comparisons. See "But this can be made worse" below.

It's already slow...

Your code restarts for every inversion and end up with \$\mathcal O(n^3)\$. That's already bad, but you can do worse.

But this can be made worse

Just increase src only in the outer while. Here's the analysis for the case:
The worst runtime we can get is for an inverse array, e.g. [5,4,3,2,1]:

[5,4,3,2,1]
[4,5,3,2,1]
[3,5,4,2,1]
[2,5,4,3,1]
[1,5,4,3,2]
...

For \$n\$ elements, we need \$1\$ comparison to move the largest element to the second position, \$2\$ elements to move the second largest to the third, and so on. In summary, we have $$1 + 2 + \ldots + (n-2) + (n - 1) = \frac{n(n-1)}{2}$$ comparisons to get the smallest value to the front. However, contrary to bubble sort, we always reset srcPos to zero. Therefore, the second smallest value won't take less time to get to the front:

[1,4,5,3,2] -- 4 comparisons for 1, 1 comparison for 5-4
[1,3,5,4,2] -- 4 comparisons for 1, 2 comparisons for 4-5, 4-3
[1,2,5,4,3] -- 4 comparisons for 1, 3 comparisons for 3-5, 3-4, 3-2

Although we should be able to only look at the subarray starting at index one, we always have the initial 4 comparisons. So for the second element, we have

$$((n-1)+1) + ((n-1)+2) + \ldots + ((n-1)+(n-3)) + ((n - 1)+(n-2))
 = (n-1)(n-2) + \frac{(n-1)(n-2)}{2}$$
comparisons. It's similar for the rest:

[1,2,5,4,3]
[1,2,4,5,3] -- 4 comparisons for 1, 3 comparisons 2, 1 comparison for 5-4
[1,2,3,5,4] -- 4 comparisons for 1, 3 comparisons 2, 2 comparison for 4-5, 4-3

If we complete the induction, we get

$$ \sum_{i=0}^n \frac{(n-i)(n-i-1)}{2} + (n-i-1)\sum_{j=1}^i (n-j) $$
which is inefficient enough. Good job there :).

Readability, reuse and testability

Readability really suffers since the swap logic is put into a single line. Also, there are several values with short names that are not related to your algorithm at all.

Furthermore, we cannot use the sort outside of that snippet. That prevents

sorting more than one array
custom sort (for example reverse, lexicographic, etc.)
testing

So first of all let's make a function:

function slowSort(arr) {
    var src = 0;
    var dest;
    var tmp;

    while(src < arr.length - 1) {
        dest = src + 1;
        while(dest < arr.length) {
            if(arr[src] > arr[dest]) {
                temp = arr[dest];
                arr[dest] = arr[src];
                arr[src] = temp;
                src = 0;
                break;
            }
            dest++;
            src++; // place this one in the outer to make it worse, but
                   // keep in mind to set `src = -1` instead.
        }
    }
}

That's a lot easier to read. Also, we can now

sort multiple times
get improvements/speed regressions for every call site
add additional comparison methods, e.g.

function slowSort(arr, comp) { ... }

test the function

Bottom line

Always try to make your code reusable, testable and readable.


Schema for allowing adding tags to entities in unrelated tables

A simple solution is to include a table reference in the tagmap instead of many id columns.

CREATE TABLE tagmap(
  TagmapID int(2) NOT NULL AUTO_INCREMENT,
  RefTable varchar(255) NOT NULL,
  RefID int(2),
  TagID int(2) NOT NULL,
  PRIMARY KEY(TagmapID),
  INDEX(RefTable, RefID),
  UNIQUE(RefTable, RefID, TagID)
);

With that approach, you can easily make other tables taggable. To retrieve the tags for a post, you'd just say

SELECT TagName FROM tags
LEFT JOIN tagmap USING TagID
WHERE RefTable = 'posts' AND RefID = 42


Merge objects in Kotlin if they are updated

To make your code understandable, you should extract the code for merging a single PersonDetail into a separate function:

fun merge(fresh: PersonDetail, fromDb: PersonDetail): PersonDetail {
}

This function is where the main complexity happens, and it should be easy to write unit tests for this part of the code. And you should definitely write unit tests, after all you're dealing with details of actual people here, so you better get it correct from the beginning.

In this merge function you can have much shorter variable names. Since you are dealing with persons only, you can remove the word person from the variable names, like I already did in the function declaration above. You can remove the word detail as well.


Just a quick observation I have made here, and this is by no means a full review, but you have some dead code here:

if ($parts) {
    $this->controller = ucfirst(array_shift($parts)) . 'Controller';
    $this->action     = array_shift($parts);
    $this->params     = ($parts) ? $parts : null;
}

It will only enter the if-block if $parts is true, and when assigning to $this->params you check it again, but it can never be null.

Therefore you should just assign $this->params = $parts;

Overall the readability of the code looks fine to me.


matplotlib adding stuff to the current figure is because you are not using the OO-interface. It is slightly clunkier, but allows way more freedom

In my view, you are mixing several things up. I would seperate the generation of the timings, the aggregation of these results and the plotting. In this way, if you want to change to another plotting library (bokeh, seaborn,...) you only need to adapt or add 1 method, and not refactor the whole thing.

imports

import pandas as pd
from functools import partial
import timeit
import numpy as np
import matplotlib.pyplot as plt

tying it together

def plot_times(functions, inputs, repeats=3, n_tests=1, file_name=""):
    timings = get_timings(functions, inputs, repeats=3, n_tests=1)
    results = aggregate_results(timings)
    fig, ax = plot_results(results)

    return fig, ax, results

This should be self-explanatory. first you generate the timings, then you aggregate the results and finally you plot the aggregations. In this way, you can test each part individually. This function returns the actual generated figure, the plot axes and the results-DataFrame so you can inspect them later on if needed. In your __main__ you can save or show the fig

get_timings

def get_timings(functions, inputs, repeats, n_tests):
    for func in functions:
        result = pd.DataFrame(index = inputs, columns = range(repeats),
            data=(timeit.Timer(partial(func, i)).repeat(repeat=repeats, number=n_tests) for i in inputs))
        yield func, result

The only change I made here is to save the individual data of one function in a pandas.DataFrame for easy aggregation afterwards. The yield makes sure these timings are only calculated when they are needed

aggregate_results

def aggregate_results(timings):
    empty_multiindex = pd.MultiIndex(levels=[[],[]], labels=[[],[]], names=['func', 'result'])
    aggregated_results = pd.DataFrame(columns=empty_multiindex)

    for func, timing in timings:
        for measurement in timing:
            aggregated_results[func.__name__, measurement] = timing[measurement]
        aggregated_results[func.__name__, 'avg'] = timing.mean(axis=1)
        aggregated_results[func.__name__, 'yerr'] = timing.std(axis=1)

    return aggregated_results

This method makes 1 big DataFrame with a MultiIndex in the columns whose first level is the function, the second label is the result. Each individual timing is saved in this DataFrame, and the average and standard deviation calculated

plot_results

def plot_results(results):
    fig, ax = plt.subplots()
    x = results.index
    for func in results.columns.levels[0]:
        y = results[func, 'avg']
        yerr = results[func, 'yerr']
        ax.errorbar(x, y, yerr=yerr, fmt='-o', label=func)

    ax.set_xlabel('Input')
    ax.set_ylabel('Time [s]')
    ax.legend()
    return fig, ax

This simply generates a plot for every func, adds the labels and the legend


def solve_maze(case_no):
    case = cases[case_no]

It'd make more sense to pass the case here, and operate on that rather then passing in the case number

    case_no += 1
    edges = case['edges']
    #quick and dirty check. Can we reach the goal?
    if case['goal'] not in sum([i.values() for i in edges.values()],[]):
        return "Case #%s: Infinity" % case_no

I avoid such quick and dirty checks. The problem is that they are easily defeated by a crafted problem. Not enough cases are really eliminated here to make it work.

    last_position = 1
    l = 0
    states = set()
    memory = [1 for i in range(1,1+case['goal'])]

It's a little odd to add one to both parameters to range and then ignore the count

    while not last_position==case['goal']:

Use !=

        direction = memory[last_position]
        memory[last_position] *= -1
        move = edges[last_position][direction]
        states.add(hash((move,tuple(memory))))

You aren't guaranteed to have distinct hashes for unequal objects so this must fail. You should really add the whole tuple to the state. Actually, you don't even need to track the states. There are are only so many possible states, and you can simply count the number of transitions, if this gets above the number of possible states, you're in an infinite loop.

        l+=1
        if len(states) != l:
            return "Case #%s: Infinity" % case_no
        last_position = move
    else:
        return "Case #%s: %d" % (case_no,len(states))

with open("/xxx/test-small.in","rb") as f:
    inp = f.read()[:-1].split("\n")

This really isn't a good way to read your input. Use f.readline() to fetch a line at  a time. It'll be much easier to parse the input that way.

    N = int(inp[0])
    cases = []
    it = 0
    for line in inp[1:]:

Wrong choice of loop. You really want to repeat the process of reading a single case N times, not do something on each line of the file.

        if line.find(" ") == -1:
            #print int(line)
            cases.append({"goal":int(line),"edges":{}})

Don't treat dictionaries like objects. It'd make more sense to pass goal and edges as parameters rather them stick in a dictionary. At least, you should prefer an object.

            it = 0
        else:
            it+=1
            cases[-1]['edges'][it] = dict(zip([1,-1],map(int,line.split())))
    for i in range(len(cases)):
        print solve_maze(i)

As for your algorithm. You can't get away with simulating all of the clearings. One can design a test case that takes over 2**39 steps to complete. So you can't simulate the straightforward process of moving one clearing at a time. But any given forest will have patterns in how the states change. You need to find a way to characterize the patterns so that you can simulate the process more quickly.


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

Learn a recent version of C

I still have my K&R first edition from 1978, however it would be a very poor choice to use for learning C today.  The version of C it teaches has been obsolete for decades.  I don't know which edition you're using (looks like a more recent one by the style of code) but it would be best to learn C99 or C11.  You may already be doing this, but it would be good to check.

Declare variables closer to where they're used

It may be a result of the book you're reading to learn C (per the previous point) but in modern C, we don't declare all of the variables at the top of the function that will be used in the entire function.  Instead, declare the variables closer to where they're first used.

Reorder functions to avoid prototypes

You can eliminate the function prototypes by rearranging the function definitions so that each function is defined before its first appearance. In this case, that simply means moving main last, below the other functions.

Use const where practical

The current version of entab doesn't alter the passed line.  This can be clearly indicated by making that parameter const:

char * entab(const char line[], int len)

Avoid frequent memory allocations

Memory allocation operations can be expensive in terms of time and are also yet another thing that can go wrong in terms of running out of memory or forgetting to free the block.  With that in mind, there are two obvious choices. One would be to pass in an output buffer and length to entab() and the other is to do the entabbing in place.  I'd advocate the latter approach since we know that an entabbed line will never be larger than the input string.

Fix bug #1

The first time through the loop, e_len is 0 and gets incremented to point to the terminating '\0', but the value is never reset to zero for the second and subsequent lines.  That's a bug.  Instead, I'd recommend changing from this

while (entabbed[e_len] != '\0') {
    e_len++;
}

To this:

for (e_len = 0; entabbed[e_len] != '\0'; ++e_len)
{}

Fix bug #2

Within the entab function, the terminating '\0' is never copied to the resulting copy of the line.  The result is that the line may or may not be properly terminated.  This is easily fixed by changing the for loop there from this:

for (i = 0; i < len; i++) {

to this:

for (i = 0; i <= len; i++) {

Eliminate return 0 at the end of main

Since C99, the compiler automatically generates the code corresponding to return 0 at the end of main so there is no need to explicitly write it.


Javascript run length encoding algorithm

Separation of concerns

The problem has two distinct, independent components:

Compute run length
Decide if two values are equal

I agree that using reduce makes sense here to compute the run length.
If you separate this computation from the equality decision,
the logic of the reducer can become a lot simpler:

  const reducer = (acc, val) => {
    if (acc.length > 0 && equals(acc[acc.length - 1][1], val)) {
      acc[acc.length - 1][0]++;
      return acc;
    }
    acc.push([1, val]);
    return acc;
  };
  return arr.reduce(reducer, []);

That is:

When the accumulator is not empty, and the last element has matching value,
then increment the count of the last element, and return the accumulator.
Append [1, val] to the accumulator.
The accumulator starts empty.

The equality condition is to be implemented.
You can even require the implementation to be passed in as parameter.

As @radarbob suggests,
it's good to get the run-length computation working without worrying about mixed value types.
The implementation of the equals function here is not interesting at all for run-length computation.
You can start with a simple const equals = (a, b) => a === b.
Having mixed values in the input doesn't affect at all the run-length computation logic.

The converse is also true: it should be possible to implement the equality logic independently from run-length.
This reduces your mental burden and helps you think clearly,
focusing on one problem at a time.
I came up with this:

  const equals = (a, b) => {
    if (a === b) {
      return true;
    }
    if (typeof(a) !== typeof(b)) {
      return false;
    }
    if (Array.isArray(a)) {
      return arrayEquals([a, b]);
    }
    return false;
  };

This implementation handles some easy basic cases,
and delegates some non-trivial ones,
such as comparing arrays.
Your arrayEquals will work nicely for the purpose.
Looking at this implementation,
it's also quite clear what kind of values are supported:
primitive and arrays only.
(As far as we can trust the externalized arrayEquals implementation...)


SQL to find users that the current user hasn't liked/disliked

Personally, I would just stick with what you have already got.

You could try something like this, although too me it doesn't look any tidier.
You would need to profile it against your database, to see if it performs any better.

SELECT *
FROM users
left outer join profile_likes on profile_likes.profile_id = users.id AND profile_likes.viewer_id = $my_user->id
left outer join profile_dislikes on profile_dislikes.profile_id = users.id AND profile_dislikes.viewer_id = $my_user->id
where users.id <> $my_user->id
having profile_likes.profile_id is null and profile_dislikes.profile_id is null


A lot of your code seems to be Hackerrank's boilerplate code, so I'll ignore that (though it could use a review), and focus on the "meat" which is:

var value = 1;
for (var j = 0; j < data[i]; j++) {
    if (j % 2 == 0)
        value *= 2;
    else value += 1;
}
process.stdout.write(value + '\n');

(It's run T times of course, but that's irrelevant for now.)

There's not a lot of code there, so there's little to review. Still, the if..else is not great, if you ask me. For one, I'd advice that you always use braces - even for one-liners. But if you don't, at least use linebreaks:

if (j % 2 == 0)
    value *= 2;
else
    value += 1;

However, you can do it all in a ternary, which I would find more appropriate here:

value += (j % 2 === 0 ? value : 1);

The parentheses aren't required, but I find they make it more readable.

Of course, you could also rely on zero being false'y in JavaScript, and just do

value += (j % 2 ? 1 : value);

A slightly faster solution to the even/odd branching would be

value += (j & 1 ? 1 : value);

In other words: If the least-significant bit is 1, the number is odd.

In all, you get:

var value = 1;
for (var j = 0; j < data[i]; j++) {
    value += (j & 1 ? 1 : value);
}
process.stdout.write(value + '\n');

Of course, there may be a purely mathematical, loop-less solution to this. But that's unfortunately not my strong suit.

Update: As mjolka points out in the comments, there is a very simple pattern to this. (And I feel pretty dumb for not realizing it.) I can't really explain it more succinctly than mjolka already has, so I'll just quote the comment here:

  Look at the first few terms: 1, 2, 3, 6, 7, 14, 15, 30, 31, ... and compare that to powers of two: 2, 4, 8, 16, 32, ...

As is obvious, the output values are all equivalent to a power of 2, minus 1 or minus 2. In code, that can be expressed as a function like so:

// calculate tree height after n cycles
function utopiaTreeHeight(n) {
  var exp = Math.ceil(n / 2) + 1,   // calculate the exponent
      value = Math.pow(2, exp) - 1; // power of 2, minus 1

  return value - (n & 1);           // subtract another 1 if n is odd, and return
}

Which means that the rest of the code is just:

for(var i = 0 ; i < data.length ; i++) {
  var value = utopiaTreeHeight(data[i]);
  process.stdout.write(value + '\n');
}

Now, that's pretty clean, I'd say. Big tip of the hat to mjolka!

Below are my previous (iterative and naïve) solutions. I'll leave them in my answer, only because there's probably something of value in there, even if this particular problem has a much more elegant solution.

(End of update.)

Now, about repeating it T times: If you're processing many test cases, it might be worth it to do some pre-processing. All you really need is to iterate to the highest cycle-count. So if you're asked to solve for data = [3, 6, 5] what you really want to just solve for N = 6 but store the intermediate values for N = 3 and N = 5 along the way. You only need to loop once; from zero to Nmax.

Of course, doing so will require extra setup, which may be less efficient than simply doing what you're doing now, if there's only one or two test cases.

Just for fun, though, one solution might be:

var cycles = data.length,          // cache this for later
    sorted = data.slice(0).sort(), // copy and sort the input values (slightly faster if you use an explicit comparison function)
    limit  = sorted[cycles - 1],   // get the max
    target = sorted.shift(),       // grab the lowest value (our first target cycle)
    value  = 1,                    // initial tree height
    values = {};                   // a place to store values

// loop to the highest cycle-count (note the range is 0..limit)
for(var n = 0 ; n <= limit ; n++) {
  while( n === target ) {
    // we reached our target cycle, so store the current value
    values[n] = value;

    // and grab the next target
    target = sorted.shift();
  }
  value += (n & 1 ? 1 : value);
}

// print results in the correct order
for(var i = 0 ; i < cycles ; i++) {
  process.stdout.write(values[data[i]] + '\n');
}

The while loop is there to handle duplicates in the input.

A simpler solution would be to simply store every value for N in 0..Nmax in an array. That tradeoff would be memory consumption. If data = [1, 923123] you'd end up storing 923121 values (~7MB at worst) you're not going to use. Crazy example, but if you don't know your input, well...

Still, such an approach could look like:

var limit = Math.max.apply(null, data),
    values = [],
    value = 1;

for(var n = 0 ; n <= limit ; n++) {
  values.push(value);
  value += (n & 1 ? 1 : value);
}

for(var i = 0 ; i < data.length ; i++) {
  process.stdout.write(values[data[i]] + '\n');
}


You should not need the n + 1, since the UnicodeString keeps track of the string's length, no matter whether it is null-terminated or not. It's in the documentation, you just need to read it.

So the line *(begin+n) = 0; is unnecessary. Especially since you tell icu that the new length is n, which means that begin[n] will be ignored anyway.

A general remark: maybe the code is even easier to read like follows:

auto len = word.length();
UChar *buf = word.getBuffer(len);
std::sort(buf, buf + len);
word.releaseBuffer(len);

I renamed n to len, renamed begin to buf and removed end altogether. Given the idiomatic C++ usage of the (begin, begin + len) pattern, it saves some code and makes the intention of the variables a little clearer.

If you want to support full unicode, you should not use UChar, since that is only a UTF-16 code unit and therefore not able to handle emojis, extended CJK ideographs, byzantine musical symbols and several more scripts starting at U+10000 and beyond.


It depends.  (By the way, as things are your Classifier::Train function is ill-formed due to missing a return type; I'll assume void.)

If you expect the value to need dynamic storage duration, use the first method, but use a smart pointer (std::unique_ptr, boost::scoped_ptr or similar).  That may remove the need for an explicitly-defined destructor; if not, remember the rule of three.

If you do not expect the value to need dynamic storage duration, use the second form.  I recommend passing trainer by const reference, but it really doesn't matter all that much.

If you can't decide, use the latter unless you have a compelling reason to use the former.


Program to check whether two strings are anagrams of each other

About the algorithm (ITS NOT CORRECT). I will still review it for you:

Passing l1 and l2 in boolean check(char[] c1,char[] c2,int l1,int l2) as argument is redundant. You can use the inherent c1.length and c2.length provided by Java.
if(count==l1 && count==l2) Any one check would do as you overruled l1!=l2 very early. Remember?
Failure cases:
"aab" and "abb" both would be called anagrams. Hope you discover that.

About the algorithm:

There are simpler better ways to check if two strings are anagram. How? Sort the strings and compare character by character.
Not impressed? Do a character count using a Map for each character and compare it for other array. And there are many more. Happy Googling.


The array_search will iterate over every element in $this->routes. That's not scalable. It would be better to reorganize $this->routes so that you can lookup keys more directly, so that your code will work like this:

if (isset($this->routes[$this->reqUri])) {
    $key = $this->routes[$this->reqUri];
    // ...
}

In this arrangement, the lookup should be in \$O(1)\$ time or close, even with large number of routes.

Do you really need the !== false here?

if ($key !== false) {

Can't it be simply:

if ($key) {

In the innermost if, since you return in both the if and the else, you could move the return statement outside:

if (isset($this->methods[$key])) {
    if ($this->methods[$key] === $this->reqMethod) {
        call_user_func($this->callables[$key]);
    } else {
        $this->defaultCallable();
    }
    return;
}

In terms of readability, I find it slightly better this way:

if ($key) {
    if (isset($this->methods[$key])) {
        if ($this->methods[$key] === $this->reqMethod) {
            call_user_func($this->callables[$key]);
            return;
        }
    } else {
        call_user_func($this->callables[$key]);
        return;
    }
}

$this->defaultCallable();

That is, the $this->defaultCallable() call appears only once instead of twice, everything else still being the same.


Write a class with some properties and indexed

The inheritance doesn't make sense. 'PlacementLocations' is the object representing a collection of 'PlacementLocation' objects.

public class PlacementLocations
{
    private List<PlacementLocation> _placementLocations;

    public PlacementLocations(List<PlacementLocation> locations)
    {
        _placementLocations = locations;
    }

    public Tuple<int, int> this[int location]
    {
        get { return new Tuple<int, int>(_placementLocations[location].Row, _placementLocations[location].Column); }
    }

    public int this[int row, int column]
    {
        get
        {
            PlacementLocation singleOrDefault =
                _placementLocations.SingleOrDefault(d => d.Column == column && d.Row == row);
            return singleOrDefault != null ? singleOrDefault.Location : 0;
        }
    }
}

Class should not contain particular initialization values: use constructor parameters instead and initialize externally:

...

var placementLocationList = new List<PlacementLocation>
{
    new PlacementLocation { Column = 1, Row = 9, Location = 1 },
    new PlacementLocation { Column = 2, Row = 9, Location = 2 },
    new PlacementLocation { Column = 3, Row = 9, Location = 3 },
    new PlacementLocation { Column = 4, Row = 9, Location = 4 },
    new PlacementLocation { Column = 5, Row = 9, Location = 5 },
};

var placementLocations = new PlacementLocations(placementLocationList);

...

Update:
if you need predefined locations list you can use some sort of factory...

public class LocationsFactory
{
    public static PlacementLocations GetPredefinedLocations()
    {
        var placementLocationList = new List<PlacementLocation>
        {
            new PlacementLocation { Column = 1, Row = 9, Location = 1 },
            new PlacementLocation { Column = 2, Row = 9, Location = 2 },
            new PlacementLocation { Column = 3, Row = 9, Location = 3 },
            new PlacementLocation { Column = 4, Row = 9, Location = 4 },
            new PlacementLocation { Column = 5, Row = 9, Location = 5 },
        };

        return new PlacementLocations(placementLocationList);
    }
}


Count how many times values has appeared in list so far

You can use a defaultdict, to remove the if v else.
To achieve this, you can do:

from collections import defaultdict
counted = defaultdict(int)
for i,v in enumerate(x):
    counted[v] += 1

To remove the need for out and enumerate you can yield on each iteration.
This would make your code very small and readable.

from collections import defaultdict

def times_so_far(list_):
    counted = defaultdict(int)
    for v in list_:
        counted[v] += 1
        yield counted[v]

print(list(times_so_far([1,1,2,3,1,3])))
#[0, 1, 0, 0, 2, 1]

It will return a generator object, hence why I use list.
If this is a problem then you can change yield to out.append() and re-add out.

This has \$O(n)\$ runtime, with a min \$O(n)\$ and maximum \$O(2n)\$ memory usage.


A few suggestions:

You're performing string manipulations, and then extracting numbers out of the string result, which is slow. The best thing to do is to ingest the data in a better format in the first place (so that the number you're extracting will be ingested in a separate numeric column). If it's not possible to do it in ingestion, then you should do it in an Update Policy.

You didn't add any filters on datetime columns, meaning you're querying the whole table. For this to work efficiently, you need all the data to be in the hot cache. Is this your case? To see the effective retention and caching policies for the table, run .show table tableName details | project RetentionPolicy, CachingPolicy.

You might want to try using summarize hint.strategy=shuffle (see this for more info).


Searching faster for a file on the drive using Python

Since you are already requiring the filename to start with the correct drive name, your target will already look like a normal valid path. So you could at least check if what the user entered is actually the correct path, short-circuiting the whole search:
def search(drive, target):
    if os.path.isfile(target):
        return os.path.abspath(target)
    ...

You should also stop looking as soon as you have found your target and use the in keyword instead of manually checking all files yourself:
    ...
    for root, dirs, files in os.walk(r"D:\\"):
        if target in files:
            return os.path.abspath(os.path.join(root, target))

Other than that, I am afraid you are mostly out of luck. There are only two ways to quickly find something in a big pile of somethings:

You search through all somethings until you find the something you are looking for.
You have a datastructure, called an index, which tells you how to find each (or at least some, including hopefully the one something you are looking for) of the somethings.

In the Unix world there is the command line tool locate, which uses a periodically updated database of files to make finding files fast (as long as they are in that database). I am not sure what the equivalent Windows (command line) tool is, though you may find some solution here. You can then call that tool using subprocess.
Of yourse, if you need this search very often (twice is probably already often enough), you could also built such an index yourself, meaning you only have to check all files once:
from collections import defaultdict

INDEX = {}

def build_index(drive):
    index = defaultdict(set)
    for root, _, files in os.walk(drive):
        for file in files:
            index[file].add(root)
    return dict(index)

def search(drive, target):
    if drive not in INDEX:
        INDEX[drive] = build_index(drive)
    root = next(iter(INDEX[drive][target]))
    return os.path.abspath(os.path.join(root, target))

Note that this arbitrarily chooses one result if a file name appears multiple times, similarly to your code which chooses the last one encountered (with the order of processing arbitrarily defined). On my machine, for example, there are 8708 files called index.js and it is not clear which one you want. It might be a better interface to return all of them instead of one arbitrary one.


Table of contents (in no particular order)
Indent your code properly!
Don't use goto for something so routine. Unless you're writing a c compiler and intend to compete with gcc or clang or you're Andrei Alexandrescu... don't use goto at all!
while loop/for loop can be used to accomplish what you need instead of goto.
Fix memory leaks. If you're in place modifying a linked list, the nodes that are removed from the list have to have their memory free'd. (In general, this is the assumption going off solely your function prototype. It's possible that all the nodes are statically allocated and it's not this function's responsibility to free them but I'm assuming the more usual case.)
Use comments to explain what you're doing. Although this isn't super complicated, since it's pretty low level, comments are a good idea.
Checking for NULL, IMO it's better to do an explicit check with == NULL rather than !l. Although it is the same and is a popular choice among C programmers (I used to do it too, it made me feel smart)... it's hard to read and is not a good idea. Personally, I only use !l to check for bool's. Others may disagree.
Better variable names. This can cut down on the amount of stuff that has to be explained in comments. Renamed p to previous and q to current. (If you really don't wanna type so much -- prev and cur)
typedef struct list_integer {
    type value;
    struct list_integer *next;
} list_integer;

list_integer *removeKFromList(list_integer * l, int k)
{

    if (l == NULL) return NULL; // empty list becomes empty list

    // remove the occurrences of k at the beginning
    while (l != NULL && l->value == k) {
        list_integer* temp = l;
        l = l->next;
        free(temp); // deallocate memory
    }

    if (l == NULL) return NULL; // list of only k's becomes empty list

    // already checked in the while loop. l->value != k
    list_integer *previous = l;
    list_integer *current = l->next;

    while (current != NULL) {
        if (current->value != k) {
            previous = current;
            current = current->next;
        } else {
            while (l != NULL && l->value == k) { // remove continuous occurrences of k
                list_integer* temp = current;
                current = current->next;
                free(temp); // deallocate memory
            }
            previous->next = current;
            if(current != NULL) {
                previous = current;
                current = current->next;
            }
        }
    }

    return l;
}

The version above keep's the OP's optimisation of not modifying the next pointer (ie p->next) multiple times if there are multiple continuous k's.
Version without this optimisation is a bit simpler
typedef struct list_integer {
    type value;
    struct list_integer *next;
} list_integer;

list_integer *removeKFromList(list_integer * l, int k)
{

    if (l == NULL) return NULL; // empty list becomes empty list

    // remove the occurrences of k at the beginning
    while (l != NULL && l->value == k) {
        list_integer* temp = l;
        l = l->next;
        free(temp); // deallocate memory
    }

    if (l == NULL) return NULL; // list of only k's becomes empty list

    // already checked in the while loop. l->value != k
    list_integer *previous = l;
    list_integer *current = l->next;

    while (current != NULL) {
        if (current->value != k) {
            previous = current;
            current = current->next;
        } else {
            list_integer* temp = current;
            current = current->next;
            previous->next = current;
            free(temp); // deallocate memory
        }
    }

    return l;
}
```


Simpler and faster code for reversing list?

Your code has some issues from my perspective.  The first that jumps out is that you are passing a pointer to a pointer to a list.   This is one level of indirection too many. Just pass a pointer to the list.  To make this easier, your list pointer in main() should just be a pointer to the first entry in the list; it should not be the first entry. In other words don't malloc space for a NODE in main().

So when you construct the list it will look like this:

 first _____
            |
            v
            -------       -------       -------       -------
  NULL <-- |p      | <--- |p     | <--- |p     | <--- |p     |
           |      n| ---> |     n| ---> |     n| ---> |     n| ---> NULL
            -------       -------       -------       -------

To reverse this list, you could take the approach given by @iaimtomisbehave, from earlier.  But this has two notable points: It needs a last pointer to the end of the list (this might be a plus) as well as first (or start/end); if you just swap last and first then you haven't really reversed the list because to traverse the list you now have to follow the prev pointers instead of following the next pointers. But there is a simple solution: just swap the prev and next pointers of each node as well as swapping first and last.

Some other points:

Naming: upper case names are usually reserved for constants. So call NODE something else: eg. Node or node.
malloc should not be cast
you malloced the string and then didn't use it.(Insert() line 5/6))
you have code to find the end of the list twice. It is a simple loop that belongs in a separate function.
Add some space to make the code look less cramped.  Note that while, for, if etc are special and deserve to be followed by an extra space: eg while (condition) (this is just my preference; others may disagree).
One variable per line.

That's enough I think :-) Here is my version of your program, for what it is worth.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct Node
{
    char *item;
    struct Node *next;
    struct Node *prev;
} Node;

static Node *last_node(Node *list)
{
    while (list->next != NULL) {
        list = list->next;
    }
    return list;
}

static Node *insert(char *data, Node *list)
{
    Node *node = malloc(sizeof(Node));
    /* should handle malloc/strdup failure... */
    node->item = strdup(data);
    node->next = NULL;

    if (list == NULL) {
        list = node;
        node->prev = NULL;
    }
    else {
        Node *last = last_node(list);
        node->prev=last;
        last->next=node;
        last = node;
    }
    return list;
}

static Node *reverse(Node *list)
{
    Node *last = NULL;

    for (;list != NULL; list = list->prev) {
        Node *prev = list->prev;
        list->prev = list->next;
        list->next = prev;
        last = list;
    }
    return last;
}

static void display(const char *msg, Node *list)
{
    printf("%s\n", msg);

    for (;list != NULL; list = list->next) {
        if (list->prev != NULL) {
            printf("<-->");
        }
        printf("%s", list->item);
    }
    printf("\n");
}

int main(int argc, char ** argv)
{
    char s[50];
    Node *list = NULL;
    (void) argc;
    (void) argv;

    printf("Enter string of words for the list.  "
           "End the list with a full-stop on a blank line: ");
    while ((scanf("%49s", s) == 1) && strcmp(s, ".")) {
        list = insert(s, list);
    }

    display("Original List is: ", list);
    list = reverse(list);
    display("Reversed List is: ", list);
    return 0;
}


Time limit exceeded in K-th symbol in Grammar (LeetCode)

It makes little difference how the row is constructed, the problem is intentionally designed such that constructing the row at all will lead to TLE. Consider that for N=30, the row would have 229 elements, that's no good. This is usually the case with competitive programming problems, they are made to make the straightforward solutions fail, that is what makes it competitive.

There are a few ways you could go about solving it, for example, you could recognize that the sequence produced is the Thue-Morse sequence, which has a simple formula to calculate an element at a given index without generating the whole sequence up to that index. The result does not depend on N.


Consider using dependency injection

What that means is "injecting" what you want to manipulate into your class (instead of relying on "global" variable), for example:

let a = 42;
function manipulateA () {
    return a = a + 24;
}
console.log(manipulateA(), a); // 66, 66

versus:

let a = 42;
function manipulate (a) {
    return a = a + 24;
}
console.log(manipulate(a), a); // 66, 42

This allows for much easier to test code, and you know exactly what will happen with everything instead of relying on something to magically happen in the global scope.

Consider this instead (using es6 and dependency injection):

class MoveOver {
  // dependency injection
  constructor ({element = document.body}) {
    this.element = element;
    this.index = 0;
  }

  startListening () {
    const mouseMove = () => {
      this.element.textContent = `mouseMove_${this.index++}`;
    }
    this.element.addEventListener('mousedown', () => {
      console.log('mouseDown');
      this.element.addEventListener('mousemove', mouseMove, false);
    }, false);
    window.addEventListener('mouseup', () => {
      console.log('mouseUp');
      this.element.removeEventListener('mousemove', mouseMove, false);
    }, false);
  }
}

const move1 = new MoveOver({element: document.getElementById('mouse')});
const move2 = new MoveOver({element: document.getElementById('mouse2')});

move1.startListening();
move2.startListening();
.cover {
  height: 200px; width: 200px;
  border: red solid 1px;
  float: left; margin: 15px;
}

In the above example we are able to add the same events to two (2) different elements, but yet still yield the same results for both


Checking if an associated object has failed to save/create

Given the current setup, the simplest thing would probably be to raise an exception using #save!:

def apply_to(listing)
  jobapp = Jobapp.new(resume: self, listing: listing)
  jobapp.save! # note the bang (!)
end

And in the controller

def apply
  set_resume
  @resume.apply_to(@listing)
  redirect_to @listing
rescue ActiveRecordError
  redirect_to @listing, alert: 'Unable to apply for job'
end

It may be worth the effort to rename your method to apply_to! (also with a bang) to make it clear that it can raise an exception.

As for why create doesn't work, it's not that it returns true - it returns the new record (and all objects except nil and false are considered "true"). To check if create actually managed to persist that record in the database, you can check record.persisted?. If true, then it was saved just fine.

So using your create version of the method, you could do

def apply
  set_resume
  jobapp = @resume.apply_to(@listing)
  if jobapp.persisted?
    redirect_to @listing
  else
    redirect_to @listing, alert: 'Unable to apply for job'
  end
end

This would also let you access jobapp.errors, if you want.

A few other things caught my eye:

set_resume should probably be in a before-filter. Or be a method that just returns a record, leaving it up to the caller to stick it in an instance variable (or not)
I imagine a jobapp belongs to a listing (and/or a resume). If so, it'd be cleaner to build it like so:

jobapp = owner.jobapps.new(other: foo)

Given that it's this simple, though, it might be something you could just do in the controller.

It's never quite clear where a join model like jobapp (which I assume is basically a join model) should be created. Should it be in the Resume model or in the Listing model? Either one makes sense. So the Solomonic solution is do neither (at least for now), and handle it in the controller:

def apply
  jobapp = @listing.jobapps.new(resume: @resume)
  if jobapp.save
    redirect_to @listing
  else
    redirect_to @listing, alert: 'Unable to apply for job'
  end
end

Lastly, you might want to tweak that error message. It seems a little "blunt" to me. Though it's the server that failed, it sounds as if the user is unable to apply for the job. "Failed to save job application" might be more appropriate


Select latest phase of objects not marked "remove"

As I wrote in my edit of the question, I came to the following solution, which I think could be better optimized, but does the job:

SELECT *
FROM (
    SELECT *
    , MAX(numericphase.phase) OVER (PARTITION BY numericphase.uuid) AS s
    FROM (
        SELECT *
        , CASE
            WHEN status = 'REM' THEN 4
            WHEN status = 'FIN' THEN 3
            WHEN status = 'START' THEN 2
            WHEN status = 'CONF' THEN 1
            ELSE -1
        END AS phase
        FROM mytable
    ) numericphase
) lastphase
WHERE phase != 4
AND s = phase
AND s > 0


Instead of creating a new Integer and throwing it away, use String.valueOf() directly.

String strInteger = String.valueOf(Float.valueOf(strFloat).intValue())


Your code appears to fail on:

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Output:
intervals : [[1 3] [2 6] [8 10] [15 18]]
comparing intervals  [1 3] and  [2 6]
comparing intervals  [2 6] and  [8 10]
comparing intervals  [8 10] and  [15 18]
merged intervals  [[1 6] [2 6] [8 10] [15 18]]

Try to simplify your code to make it more readable. For example,
package main

import (
    "fmt"
    "sort"
)

func merge(intervals [][]int) [][]int {
    const start, end = 0, 1

    var merged [][]int

    if len(intervals) > 1 {
        sort.Slice(intervals, func(i, j int) bool {
            return intervals[i][start] < intervals[j][start]
        })
    }

    for _, interval := range intervals {
        last := len(merged) - 1
        if last < 0 || interval[start] > merged[last][end] {
            merged = append(merged,
                []int{start: interval[start], end: interval[end]},
            )
        } else if interval[end] > merged[last][end] {
            merged[last][end] = interval[end]
        }
    }

    return merged[:len(merged):len(merged)]
}

func main() {
    tests := []struct {
        intervals [][]int
    }{
        {[][]int{{1, 3}, {2, 6}, {8, 10}, {15, 18}}},
        {[][]int{{1, 4}, {4, 5}}},
        {[][]int{{1, 2}}},
        {[][]int{}},
        {[][]int{{7, 10}, {3, 4}, {2, 5}}},
    }

    for _, tt := range tests {
        fmt.Print(tt.intervals)
        fmt.Println(" ->", merge(tt.intervals))
    }
}

Playground: https://play.golang.org/p/Akgsws42JfX
Output:
[[1 3] [2 6] [8 10] [15 18]] -> [[1 6] [8 10] [15 18]]
[[1 4] [4 5]] -> [[1 5]]
[[1 2]] -> [[1 2]]
[] -> []
[[7 10] [3 4] [2 5]] -> [[2 5] [7 10]]


You have some cut and pasted code which can be re-factored by comparing already_voted with the direction rather than with 'up' and 'down' specifically.

if ($already_voted === false) {
    $this->db->insert('vote', $data);
    return true;
}
elseif ($already_voted == $direction) {
    return false;
}
else {
    $this->db->where(array('user_id' => $user_id, 'pronun_id' => $pronun_id));
    $this->db->update('vote', array('direction' => $direction));
    return true;
}


Jaccard distance between strings in Rust

Let's start by removing unused code, the whole normalize function and the line s1_shingles.len() as f64.

Then, in order to actually be able to call your functions easily, we change all String arguments into &str. You usually want to accept &str as more types can provide it. In this case, string literals are the big example.

Let's do shingles in a big bang!

fn shingles(s: &str) -> HashSet<String> {
    let chars: Vec<_> = s.chars().collect();
    chars.windows(2).map(|w| w.iter().cloned().collect()).collect()
}

We start by getting all the characters once into a vector. Now that we have a slice (through the Vec), we can use windows, which gives overlapping views into the slice. We then convert each window into an iterator of char using cloned and then into a string using collect. We convert  the overall iterator into a HashSet, also using collect. Look at that type inference go!

Note that now we have a parameter to windows that allows you to extend to arbitrary-sized n-grams!

The other optimization is to avoid collecting into a collection if we just want the count of elements:

let inter = s1_shingles.intersection(&s2_shingles).count();
let union = s1_shingles.union(&s2_shingles).count();

All together, it now looks like:

use std::collections::HashSet;

fn shingles(s: &str) -> HashSet<String> {
    let chars: Vec<_> = s.chars().collect();
    chars.windows(2).map(|w| w.iter().cloned().collect()).collect()
}

fn jaccard_distance(s1: &str, s2: &str) -> f64 {
    let s1_shingles = shingles(s1);
    let s2_shingles = shingles(s2);
    let inter = s1_shingles.intersection(&s2_shingles).count();
    let union = s1_shingles.union(&s2_shingles).count();
    (inter as f64) / (union as f64)
}

fn main() {
    println!("{}", jaccard_distance("Pear", "Peach"));
}

Edit

And of course now I see that if I were to scroll down a bit, I'd see that you do use normalize. Oops! You should still accept a &str, the only change you need to make is to take a reference to the Strings:

println!("'{}' vs '{}' ... \t {}", s1, s2,
         jaccard_distance(&normal_s1, &normal_s2));


Stack having push, pop and return min in O(1)

The general algorithm is great. At first, I thought you were overwriting the value with the min value, though, and it's because the fact that the Node stores two values is not very visible. A comment would help a lot here, and separating the logic in to a few lines too. This line:

s1.push(new Node(x,Math.min(s1.peek().min, x)));

should be:

int previousMin = backingStack.peek().minSoFar;
int minSoFar = Math.min(previousMin, value);
backingStack.push(new Node(value, minSoFar));

Note that I have also renamed all your variables. x is a poor name for a value. An x is a coordinate. s1 is another poor name, because where is s0, s2, etc... and what does s mean? min is not horrible, but it gives no indication of what it is the minimum of... what the context is.

Then, why are you using a Stack as the back-end implementation? I know it seems logical to use java.util.Stack, but you should know that it is not a recommended class any more. Stacks should be implemented over something that implements the Deque interface like java.util.LinkedList. The existing Stack class is bad because it is based on top of Vector which is a synchronized class that has a few implementation issues that are not recommended. The Stack class has this to say: "A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.". The Vector class has this to say: "Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector."

So, Stack is bad. I would use:

private final Deque<Node> stack = new LinkedList<>();

Now, about the pop() method. It is a very C-like thing to split the pop() and "get" methods. Java, and most other languages, return the top value with the pop() call and avoid the need for a second call. Your pop() should return a value. You also need an isEmpty() Method so that people know when they have run out of data before they get a NoSuchElementException.

Oh, and the Node class can be private.

So, something like:

public class MinStack {

    private final Deque<Node> stack = new LinkedList<>();

    public void push(int value) {
        if(stack.isEmpty()) {
            stack.addFirst(new Node(value, value));
        } else {
            int minSoFar = Math.min(value, stack.getFirst().stackMin);
            stack.push(new Node(value, minSoFar));
        }
    }

    public boolean isEmpty() {
        return stack.isEmpty();
    }

    public int pop() {
        return stack.removeFirst().value;
    }

    public int peek() {
        return stack.getFirst().value;
    }

    public int getMin() {
        return stack.getFirst().stackMin;
    }

    private static class Node{
        int value;
        int stackMin;
        public Node(int val, int min) {
            value = val;
            stackMin = min;
        }
    }
}


Repeated Switches

I'm not sure what you mean by Strategy Pattern (never seen the term before), but judging by Wikipedia, I imagine you are referring to the idea of replacing the pair of switch statements, which are liable to fall out of sync and create hard-to-find bugs, with a method to look up the key (e.g. a mapping from "Role" to user => user.Role and such) and then just switch on the SortingOrder, or a method to perform the sort itself (I might be inclined to do both). This is a great idea!

This can be as complex or simple as you like, because it is abstracted away. It should pay off to simply move the existing switch into a method:

delegate IComparable UserKey(User user);

private static UserKey TranslateSortExpression(string sortExpression)
{
    switch (sortExpression)
    {
        case "Role":
            return user => user.Role;
        case "Policy":
            return user => user.Policy;
        default:
            return user => user.Name;
    }
}

private void SortUsers(ref List<User> userList)
{
    UserKey sortingKey = TranslateSortExpression(SortExpression);

    if (SortOrder == SortingOrder.Ascending)
    {
        userList = userList.OrderBy(sortingKey).ToList();
    }
    else
    {
        userList = userList.OrderByDescending(sortingKey).ToList();
    }
}

A non-obvious benefit of pulling out the expression translator is that by having it return values, the compiler will ensure that it always returns a result. Currently, if you'd added an incomplete code-path by accident you may not notice, as your code would silently fail.

Anyhow, the code remains simple, has definitely become more maintainable, and now you have an obvious place to modify the code (e.g. to if you wanted to look up the Key delegate from a dictionary (which could allow you to have 'user keys' or all manner of extensibility)).

ref List<User>

It is clear why you have done this, but it is a tad scary. My first assumption was that this code was performing an in-place sort, and why it is ref isn't necessary clear to the caller (though thankfully C# makes you acknowledge this at the call site).

Unless you have good reason to duplicate the list, you should consider an inplace sort (e.g. using List.Sort(...), though this requires writing a comparer). If not, I would consider changing the method signature so that it takes in one list and returns another. As lovely as ref variables are, explicitly returning the new list will encourage cleaner calling code (i.e. not reusing a variable name for the unsorted and then sorted list) and make the method behaviour more obvious.

Either way, you should considering adding inline documentation to this method (\\\ <summary> etc.) to remind people of the chosen behaviour.

As before, returning also gives the compiler a chance to check you haven't omitted anything. Imagine the misery that could stem from no replacing the list, and finding that some backing list you are expecting to be cloned is being mysteriously modified by some code that is operating on the sorted list (I'm not saying I expect your code will do this, but it's the sort of misery inducing error that can take all day to debug because the code doesn't fail quickly (I'm a big proponent of fail-fast: the best time to fail is at compile time)).

Furthermore, if you return a different list, it can be of a different type. If your signature looked like

private void IList<User> SortUsers(IReadOnlyList<User> unsortedUserList);

then the behaviour becomes apparent (Is it an inplace sort? No, I pass it a readonly list! Where is the output? It's a return value!)

I'll throw in a comment here about using interfaces instead of concrete implementations (e.g. IList<T> instead of List<T>) where possible. It allows people to use their own implementations (which keeps code clean and potentially more efficient) and to exploit type-variant generics (interfaces can be variant, but types cannot (IList<T> is invariant, so it doesn't apply here (though IReadOnlyList<T> is covariant))

A word about enums

You should be made aware (if you are not already) that C# enums are not type safe (they are pretty dreadful). You might consider adding an explicit check for SortingOrder.Descending and throwing if any other value is passed in (e.g. (SortingOrder)12)

Instance method

Is there a good reason this is an instance method and not a static method? If you can't think of one, then it probably should be static, otherwise another programmer may start to wonder why. Static methods just 'look' honest, because they can't change the state of instances unexpectedly (atleast, not in sane systems).

I don't know enough about the layout of your code to say whether this should or should not be static, but it's worth pondering if you haven't though about it yet.

(I note that SortExpression isn't a parameter, so it is presumably an instance member, which may be a good reason to keep this virtual, but again, not enough info in the question for us really to comment on this)


Time limit of a c program while calculating factorial of numbers in c

The best solution is only to compute the factorials you need and only compute them once.

Read all the user input find the maximum value.
Generate the factorials for all values upto the max
Note: Saving them as you go:
Print the factorial values by looking up the result you generated in 2.

So lets look at the code:

I would not bother dynamically allocating the data storage.

    b=(int *)malloc(n*sizeof(int));

The question specifically limits the maximum value of n to 100.

    int b[101]; // should be suffecient

When reading values this should work (if you assume that the input is good).

        scanf("%d",&b[i]);

But the question states that the input is one value per line. Personally I would validate that there is one value per line.

Here you are calculating the factorial multiple times:

    for(i=0;i<n;i++)
       factorial(b[i]);  // Factorial is O(n)
                         // Thus this loop is O(n^2)

Technically you only need to call factorial once. If you calculate factorial for 'n' you need to calculate the factorial for 'n-1' (its how it is defined). If you store the numbers then you only need to look up the values to print it once they have been calculated.

It seems like you calculate this value each time.

    float p=0.0;
    for(i=2;i<=N;i++)
    p=p+log10(i);

The worst case scenario is that you need to calculate this for a value of 100. You only need to calculate this one for 100. Also you can calculate it off line and now it is a const expression.

This is then a const expression and thus you don't need to calculating it.

    b=(int *)malloc(d*sizeof(int));

But you do need 100 of them so you can store all intermediate values:

You don't need to loop over an array to initialize it:

    for(i=1;i<d;i++)
        b[i]=0;

You can initialize it already zero'd out. For dynamic memory use calloc() for automatic arrays use = {0};

So the above two can be combined into;

    const int d = <pre-calculated value>;
    int b[100][d] = {0};
    b[0][0] = 1;
    b[1][0] = 1;


Summation of Arithmetic Progression Modulo Series

Don't use underscore as a prefix. In most situations this is a reserved identifier. Defiantly never use double underscore in an identifier. This is reserved in all situations.

__argc  /// This is so wrong. It will break.

Read a couple of other C++ reviews. They all explain why this is a bad idea:

using namespace std;

This is not old school C. You don't need to declare the variables at the top of the function.

long N, Q, *boxes;

Declare them as close to the point of use as possible. This becomes important when your types have constructor/destructor (as they execute code). But it also makes the code easier to read as the type information is close to the usage of the object.

Please declare one variable per line (easier to read).

long    N;
long    Q;
long*   boxes; // The * belongs close to the type (as it is part of the type info).
               // PS you probably should not be using pointers. In modern C++ they
               // are vanishingly rare (as there is no ownership semantics associated
               // with a pointer).

Don't do this.

std::ifstream* infile = !filepath.empty() ? new std::ifstream(filepath.c_str()) : static_cast<std::ifstream*>(&std::cin)

Should I call delete on this? Yes if it is a file. No if it is std::cin. So not a good solution. Also std::cin is not a file stream so casting it is going to do nasty things. You should never cast things (it means you have something wrong with your design (or you are working at very low level (which most people should not be doing))).

But they are both std::istream. So you could do this.

std::ifstream   file;
if (!filepath.empty()) {
    file.open(filepath);       // Modern C++ allows std::string here.
}

std::istream& infile = !filepath.empty()
                             ? file
                             : std::cin;

You may want to check that the read works:

*infile >> N >> Q;

Very easily done with:

if (infile >> N >> Q) {
    // Read was good.
    // Do stuff.
}

Main is special. So does not need a return code.

return 0;

So if your application never fails (ie always returns 0). Use this info. A missing return in main is an indication that the application never fails.


I doubt FIRST_VALUE is necessary since you have where f.rownum = 1;


Data structure and movement for tilt maze

I think that for this situation you can just represent your maze as a matrix of boolean values. The boolean values can be used to indicate whether there is a wall for that position.

Here's an example (with true indicating that the right side of the cell doesn't have a wall):

  __ __ __ __
 |__   |__   |           [[true,  false, true,  false]
 |  |  |     |            [false, false, true,  false],
 |  |   __|  |      =>    [false, true,  false, false],
 |     |   __|            [true,  false, true,  false],
 |__|__|__ __|            [false, false, true,  false]]

The given example matrix includes values for vertical walls. I only need to include information about the right direction because I can look at the cell at (x - 1) to get wall information for the left side of the cell.

You'll need a separate matrix for horizontal walls (for a total of two matrices). The top, bottom, and left edges implicitly have a wall.

Using this representation, you should be able to calculate your end point in a time proportional to the distance between an end and start point. The ball only needs to know its (x, y) position.

Your walls likely don't have to be their own class for this problem. If you ever want to extend your program such that landing on specific types of walls (say a fire wall) results in different behavior, then objects may be helpful.

Even in that case, I would say that using an enum may be sufficient.


Django class-based generic views - am I doing it right?

This looks pretty good -- views should generally be pretty minimal. These seem pretty short, and most of what you've done so far seems appropriate.

One pattern you might think about is using a mixin to dry things out a touch more. Eg, you have all your dispatch methods decorated login_required. If you created a LoginMixin, with and just decorated the dispatch method there, you could loose a few repetitions. Mixins are also nice to have, as you can stash other repetitive elements in them as needed.


One problem in your current code is that you allocate the merged list, that could be what the user want but that not very flexible, a better way would be to consume the list, and let the user do a copy before if needed.

One other problem is that you have spaghetti code, it's very difficult to maintain and error prone.

you should also use generic to allow an user to have any type in your linked list.

To solve these problem you could use recursion, the typical use case match yours, so I would simply rework all your code to use it:

type Link<T> = Option<Box<Node<T>>>;

#[derive(Debug, Clone)]
pub struct Node<T> {
    elem: T,
    next: Link<T>,
}

impl<T> Node<T> {
    // rework of new to make it more flexible
    fn new(elem: T, next: Link<T>) -> Self {
        Self { elem, next }
    }

    // next allow to change to linked node and to return the old one
    fn next(&mut self, next: Link<T>) -> Link<T> {
        std::mem::replace(&mut self.next, next)
    }

    fn elem(&self) -> &T {
        &self.elem
    }

    // now we take by value and allow user to have a flexible control with f
    fn merge_by<F>(a: Link<T>, b: Link<T>, accu: Link<T>, f: F) -> Link<T>
    where
        F: Fn(&T, &T) -> bool,
    {
        match (a, b) {
            (Some(mut a), Some(mut b)) => {
                if f(a.elem(), b.elem()) {
                    Self::merge_by(a.next(accu), Some(b), Some(a), f)
                } else {
                    Self::merge_by(Some(a), b.next(accu), Some(b), f)
                }
            }
            (Some(a), None) => Self::rev(accu, Some(a)),
            (None, Some(b)) => Self::rev(accu, Some(b)),
            (None, None) => Self::rev(accu, None),
        }
    }

    // rev is needed when you deal with list
    fn rev(list: Link<T>, accu: Link<T>) -> Link<T> {
        match list {
            Some(mut list) => Self::rev(list.next(accu), Some(list)),
            None => accu,
        }
    }

}

fn main() {
    let a = Some(Box::new(Node::new(21, Some(Box::new(Node::new(42, None))))));
    println!("{:#?}", a);

    let b = Some(Box::new(Node::new(1, Some(Box::new(Node::new(2, None))))));
    println!("{:#?}", b);

    let c = Node::merge_by(a, b, None, std::cmp::PartialEq::eq);
    println!("{:#?}", c);
}


Decode Cæsar Cypher by Checking all Keyspaces

You could use else instead of continue to mark the 2 potential results of your test. You get something like :

def testCaesar(ciphertext):
    for testkey in range(0,25):
        decoded = ''   # <--- uglyness
        for c in ciphertext.upper():
            if not c.isalpha():
                decoded += c
            else:
                c = ord(c) # this is here to improve readability of line below. Is there a better way?
                decoded += chr(c + testkey if c + testkey < 90 else c - testkey)
        print('{0} : Rot{1} Caesar').format(decoded, str(testkey))
        checkMatch(decoded, testkey, 'Caesar')

Now, you've got some duplicated logic you could try to remove. You could use a new variable like :

def testCaesar(ciphertext):
    for testkey in range(0,25):
        decoded = ''   # <--- uglyness
        for c in ciphertext.upper():
            if not c.isalpha():
                decoded_c = c
            else:
                c = ord(c) # this is here to improve readability of line below. Is there a better way?
                decoded_c = chr(c + testkey if c + testkey < 90 else c - testkey)
            decoded += decoded_c
        print('{0} : Rot{1} Caesar').format(decoded, str(testkey))
        checkMatch(decoded, testkey, 'Caesar')

Or you could define a function for this :

def decode_char(c, key):
    if not c.isalpha():
        return c
    else:
        c = ord(c) # this is here to improve readability of line below. Is there a better way?
        return chr(c + testkey if c + testkey < 90 else c - testkey)

def testCaesar(ciphertext):
    for testkey in range(0,25):
        decoded = ''   # <--- uglyness
        for c in ciphertext.upper():
            decoded += decode_char(c, testkey)
        print('{0} : Rot{1} Caesar').format(decoded, str(testkey))
        checkMatch(decoded, testkey, 'Caesar')

Now, Python has a style guide called PEP8 and it says :

  Do not rely on CPython's efficient implementation of in-place string
  concatenation for statements in the form a += b or a = a + b . This
  optimization is fragile even in CPython (it only works for some types)
  and isn't present at all in implementations that don't use
  refcounting. In performance sensitive parts of the library, the
  ''.join() form should be used instead. This will ensure that
  concatenation occurs in linear time across various implementations.

This can be easily done now :

decoded = ''.join(decode_char(c, testkey) for c in ciphertext.upper())

Also, a tiny optimisation could be to call upper() once and only once.


Check if we can form a word across words in a sentence

Staying close to your original appraoch, you could use another for loop with an else instead of try/except and while. The else is triggered when the inner loop has ended normally, without the break, i.e. when there are no more parts left in the sentence.

def can_spell(sentence, word):
    words_iter = iter(sentence.split())
    for char in word:
        for part in words_iter:
            if char in part:
                break
        else:
            return False
    return True

Or, you could use a nested generator expression checking that all characters in the word are in any of the remaining parts of the sentence-iterator. This works since any will only consume as many items from the iterator as necessary until it finds a match.

def can_spell(sentence, word):
    words_iter = iter(sentence.split())
    return all(any(char in part for part in words_iter) for char in word)

Following an entirely different route, you could use a regular expression, joining the characters of the word such that between each character there has to be at least one space (and, optionally, any other characters), e.g. b.* .*o.* .*o.* .*m for boom, and check if that regular expression can be found in the sentence:

import re
def can_spell(sentence, word):
    return re.search('.* .*'.join(word), sentence) is not None