The expression

and . map ($ x) . map ($ y) . map ($ z) . map test $ ps

contains several map calls connected with .. But since map f . map g === map (f . g), we can simplify it as

and . map (($ x) . ($ y) . ($ z) . test) $ ps

or more concisely

and . map (\g -> test g x y z) $ ps

Also and . map p can be simplified by all, so finally we get

all (\g -> test g x y z) ps

Just one more note, please post code that compiles, especially for CR, it's much easier to work with; see http://sscce.org/


Alternative std::function implementation for lambdas

Questions & answers
“Are there any drawbacks to my implementation compared to the traditional implementation of std::function using heap allocation and virtual calls? Perhaps statically allocating the lambda is not a good idea?”
Yes, definitely a bad idea, with numerous drawbacks.
Because there are no compile-time checks to ensure that you’re actually using a lambda, this type is very brittle and very dangerous. Today I may write code like this:
auto x = 0;
auto y = 0;

auto func_x = [&x] { ++(*x); };
auto func_y = [&y] { ++(*y); };

// ... later:
auto function_x = Function<void>{func_x};
auto function_y = Function<void>{func_y};

No problems there. (Well, I mean, yes, problems, but not for this specific presumed use case. But we’ll get back to that.)
But then, later in the development process, someone refactors those two lambdas into this:
struct indirect_incrementer
{
    int* p_val = nullptr;

    auto operator()() { ++(*p_val); }
};

// then the following two lines:
//auto func_x = [&x] { ++(*x); };
//auto func_y = [&y] { ++(*y); };
// become:
auto func_x = indirect_incrementer{&x};
auto func_y = indirect_incrementer{&y};

It’s an innocent and perfectly logical refactor… but now everything blows up, because your assumption that every function object type Function is constructed with no longer holds. The static variable function is initialized with a copy of func_x, and so calling function_y does not call func_y, it calls func_x.
This isn’t just a problem with using function objects. Even if you somehow completely banned the use of function objects with Function—like, say, with some kind of linter or something—and made 100% sure that Function is always called with a legit lambda object, the problem still exists. Because despite your thinking, it is possible for a lambda type to be non-unique. It’s even quite trivial to do… just call the function that contains the lambda more than once:
auto render()
{
    // ... [snip] ...

    // somewhere in your render function, you use Function:
    auto func = Function<int, int>{[&] (int i) { return ++i; }};

    // ... [snip] ...
}

// elsewhere, in your main game loop:
while (not done)
{
    input();
    update();
    render(); // <- !!!
}

render() is called in a loop, but only the first loop will initialize the static function variable. Meaning every other time you use func, it will be with dangling references to the locals in that first render() call.
Now you could “fix” that problem with various hacks, basically detecting whether function was previously initialized, or counting the number of times it was initialized, or something like that. But it won’t fix the other problems.
The other big problem with using a static variable to hold a copy of the lambda is that you’re quietly cheating C++’s scope rules. This could lead to frustrating and nasty surprises. For example:
auto p_weak = std::weak_ptr<int>{};

// in some more restricted scope:
{
    auto p = std::make_shared<int>();
    p_weak = p;

    auto func = Function<void>{[p] { if (p) ++(*p); }};

    // use func somehow

    // scope is ending, so func and p are being destroyed, right?
    //
    // ... *right*?
}

if (auto p = p_weak.lock(); p)
    std::cerr << "memory leak!";

Turns out, p is never actually destructed; the lambda takes a copy, which is then copied into the static function variable, which then holds on to it… forever (well, until after main() returns, at least). This is not just a shared_ptr problem; I just used shared_ptr to be able to access otherwise lost memory. Any value that gets captured by the lambda is never destructed during the lifetime of the program. In other words, the more you use Function—even when every use avoids the other problems mentioned—the more you leak memory.
That’s probably why you’re seeing such large increases in speed: the function object is only being copy-constructed once—even when that’s incorrect—and it’s never being destructed.
(Also, std::function has a ton of very important and useful other abilities and benefits Function doesn’t offer, like the ability to be null-constructed, and reseated. Mere type-erasure is useful, I suppose, but probably not useful enough on its own… especially when simple function pointers can do that (and more!).)
So yes, using a static variable to get around dynamic allocation is not a good idea.
Code review
template <typename Lambda>
Function(Lambda f) {
static auto function = f;
func = + [] (Args... args) -> R {
    return function(args...);
};
};

Proper indentation would definitely help make this more readable. It would also highlight the stray semicolon you have at the end.
The fact that you’re copying f into function makes the whole class unusable with move-only lambda types:
auto p = std::make_unique<int>();

auto lambda_p = [p = std::move(p)] { if (p) { *p = 42; } };

auto func_p = Function<void>{lambda_p}; // won't compile

// (also, as mentioned previously, p won't ever be freed)

You should also use forwarding references in all the function calls. Right now every function argument will be taken by-value, which will be at least slow, and probably won’t compile in a lot of cases.
Function(const Function& other) : func(other.func) {}

This is entirely unnecessary.
inline auto operator() (Args... args) {
    return func(args...);
}

The inline keyword does nothing here.
Again, you should really be using forwarding references.
The whole interface of Function is also rather clunky. It seems specious to have to give the return and argument types, when they’re obvious and deduce-able from the lambda itself. It would be much nicer to be able to write:
auto f1 = Function{[&] (int z) {return x + y + z}};
// f1 is deduced as Function<int, int>

This is a situation where deduction guides would be useful.
Summary
You can’t get away with avoiding having function object wrappers actually wrap the function objects. Put that way, it should seem pretty obvious.
Your type-erasing wrapper either needs to dynamically allocate the memory to copy a function object, or use the small object optimization, or both. Trying to hide the wrapped object in a static variable is cheating. You may get away with it for a little while… but you will eventually be caught, either via memory leaks, reading/writing dangling references, or simply reading/writing to the wrong objects.


Multithread resource producer and consumer algorithm

I'll look first at some general programming principles as would be applicable to a single threaded queue, and then I'll look at the concurrency concerns.

First, if something can fail, it must be able to indicate to calling code that it has failed. In some cases, if failure means that something has gone really quite badly wrong, the way to indicate that would be with exceptions. In other cases some cases it would be by returning some sort of success code. In other cases you should rewrite the code so that it cannot fail, perhaps in this case by waiting for the buffer to get some space. However, your add_frame doesn't handle this. If the buffer is full then it prints to standard output (which in most programs is not even being monitored) but as far as the producer is concerned its image has been sent into the system and will be processed in due course. Instead, it's just gone nowhere.

As a matter of style, it is generally not advised to use using namespace, and even more so doing it twice in the same file. It's better to be explicit: use std::cout and cv::Mat. In this case in particular, there is an annoying amount of overlap between OpenCV function and object names and the standard library ones. OpenCV also supplies such things as abs and Vector (although not vector) and confusion about which you're using is like a trail of honey for bugs to find your code!

Also on style,

MAX_BUFFER_SIZE

  Do not use ALL_CAPS for constants just because constants used to be macros.

Thus sayeth the style guide.

Unless MAX_BUFFER_SIZE is actually a preprocessor macro, don't use capitals. If MAX_BUFFER_SIZE is a preprocessor macro, change it to be a constexpr.

In terms of program architecture, a thread safe queue is quite a general utility method, and one that is conceptually distinct from a camera. It would probably be better to move all this code (together with the buffer, mutexes, etc) to its own class and its own file.

Because it is such a general utility, it is perhaps worthwhile templating it so that you could use a similar queue for datatypes other than cv::Mat. The only thing that currently interferes with that is the clone() call.

Because cv::Mat is an inherently costly data type, it is worth thinking quite hard about whether each clone() call is needed. By default I would not expect a queue to be deep copying its input. In a producer/consumer context, I would expect that the producer pushes to the queue once it is done creating the object, and has no further use. Therefore I would suggest that the clone() can probably be removed. It is definitely unnecessary to have a clone taken on entering and on leaving the queue! (If in fact the producer does need to hold onto the image, and further needs to ensure that the consumer doesn't write to or otherwise mess with that image, it would be more explicit to do the clone before it gets into add_frame.)

Mat ret = buffer.back().clone();
buffer.front().release();
buffer.pop();

This just looks wrong to me. If the image at the back of the buffer is the one that you're returning, why is it the image at the front of the buffer that you're releasing? Further, why are you releasing it at all? The cv::Mat destructor calls release(), so as soon as the reference counter decides you're done with it. Combined with not wanting to clone if possible, I'd expect something more like

cv::Mat ret = buffer.front();
buffer.pop;

Edit: I have noticed that the second and third lines of this got caught up in your edit to switch from back to front, and the first was missed. So it's probably just an editing bug rather than a conceptual one, and a very easy fix. I would still question the clone() and release() though.

Now for concurrency. Please note that I don't have enough context to run this code, much less extensively test it. Concurrency of course needs very extensive testing, because the bugs it produces tend to be intermittent.

I am inherently suspicious of this atomic isEmpty_buffer flag. If you can't directly check buffer.empty() because it may not be updated perfectly in sync with buffer, you also cannot rely on this external atomic variable which will also not be updated in sync with buffer.

I do not believe that a shared_timed_mutex is suitable for this use case. It is generally used when some jobs are guaranteed not to mutate the data structure. If threads aren't going to change anything, you can have as many of them swarming over it at once as you want, and hence shared becomes relevant. The mutex only needs to make sure that threads which do change things get exclusive access, so that a thread which is only reading doesn't read half the state from before an update and half after. (And also so that two updates don't clash) However this is not what's happening here: both the producer and the consumer change the data structure by pushing and popping.

It might in fact work out okay if you guarantee that there is never more than one consumer, in which case you're not really using the shared aspect of the mutex at all. If this is the case you should be very explicit about your assumptions.

Presuming that you selected instead a more conventional mutex, your

while (isEmpty_buffer.load()) {

}

is still not enough to prevent things from breaking if there are multiple consumers. It is outside the lock, which means that when the queue has one element in it, two consumers could both get past that check and queue up in front of the mutex. The first consumer would go through, pop the element, and unlock the mutex on its way out. Then the second consumer would go through, pop against the empty buffer, and crash and burn.


Armstrong numbers in a given range using Java 8

Integer.toString(n).length() can be assigned to its own variable.

If you wanted to stream the while loop, I suppose you could split a toString() version of the number via toCharArray() and then calculate the value for each digit individually, then summing the result via the sum function.

I don't know whether that'd qualify as "more elegant", though. You would get rid of c and temp as variables by doing that.


Scraping urls asynchronous including exception handling

tasks = []
while urls:
    tasks.append(fetch(session, urls.pop()))

can be largely simplified to

tasks = [fetch(session, url) for url in urls]

  Is it possible to remove the result of a specific url from results in case of an exception - making return (url, '') unnecessary?

Yes, somewhat. asyncio.gather accept a return_exceptions parameters. Set it to True to avoid a single exception failing the gather call. You must filter them out afterwards anyway:

import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url, ssl=False) as response:
        return await response.text()

async def main():
    urls = [
        'http://www.python.org',
        'http://www.jython.org',
        'http://www.pypy.org'
    ]
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)

    for url, result in zip(urls, results):
        if not isinstance(result, Exception):
            print(f'{url}: {len(result)}')
        else:
            print(f'{url} FAILED')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()


Creating 28 checkboxes with a common name and different values

It seems to me that what you really need to do is change the view code. For example, if you do this:

<input type="checkbox" name="Timeschedule" id="checkbox1" value="OneTime">
<input type="checkbox" name="Timeschedule" id="checkbox2" value="Weekly">

That will automatically bind to the Timeschedule property on your SubscriptionPlanCreateViewModel. However, if the user selects multiple checkboxes, the values will probably come across as comma-separated. You can either make Timeschedule an array (which would probably better represent what you're doing from a data perspective) or you can simply replace the commas with " | " to produce the string you say you want in your comments.


It's a nice solution, but very long for a relatively simple task.

First, note that the cipher is called "Vigenère", so vignere would be considered a misspelling.

The type definitions…

type Secret = String
type PlainText = String
type CipherText = String

… provide an illusion of type safety, where there actually isn't any.  They are all just Strings.

All of the helper functions (encode, decode, shift, rightShift, leftShift, and encodeString) could just be reduced to a single function:

import Data.Char (chr, ord)

shift :: (Int -> Int -> Int) -> Char -> Char -> Char
shift op offset ch = numToChar $ (charToNum ch) `op` (charToNum offset)
  where
    charToNum ch = ord ch - ord 'A'
    numToChar n = chr $ (n `mod` 26) + ord 'A'

Hiding the charToNum and numToChar helpers makes it easier to see what calls what.

With the generalized shift function defined, the enciphering and deciphering routines could each be one-liners:

vigenere :: String -> String -> String
vigenere secret = zipWith (shift (+)) (cycle secret) . concat . words

unvigenere :: String -> String -> String
unvigenere secret = zipWith (shift (-)) (cycle secret) . concat . words

Here, I've written them using point-free style to emphasize the fact that vigenere secret acts as an enciphering filter on the text.


Dynamic two-column list, "Vertical Wrap"

Well, this is more concise, and it should be easy enough to scale:

<?php
$assets = array('Bag', 'Charger', 'Power Cable', 'Video Cable', 'Mouse', 'Keyboard', 'Test', 'Test 2', 'Test 3');

$half   = ceil(count($assets)/2);

$columns = array(
  array_slice($assets, 0, $half), // first half
  array_slice($assets, $half)     // second half
);

foreach( $columns as $index => $column ) {
  $index += 1;
  echo "

" . implode("

", $column) . "

";
}
?>

Basically, it's using more built-in PHP functions and constructs (array_slice, implode, foreach) but is functionally identical to the original.


Getting JSON with jQuery and creating lists with click events calling more jQuery and JSON

Two small nickpicks at the start:

Empty HTML lists (ul, ol) are strictly spoken invalid. They should contain at least one list item. That said, I believe there is no browser limitation or other technical reason an empty list shouldn't work.
It is custom for the names of functions, variables and object fields in JavaScript to be written with a small letter at the beginning.

You can optimize adding the list item to the list, by using .map() to create the items and appending them all at once.

$('#VerticalMenu')
  .append(
    $(sections).map(function () {
      $('<li/>')
      // ...
    })
  );

BTW, since sections is an array of simple JavaScript objects and not DOM objects it's a bit weird to wrap them in a jQuery object ($(sections).each(...)), because jQuery unwraps them immediately anyway. You should use $.each(sections, ... ) (or $.map(sections, ... )) instead.

You are assigning all items in your lists the same class (Section and SubSection respectively). Unless you remove the class later, this is usually a sign of wrong CSS design. If you leave out the class, then instead of the selector .Section { ... } you can use a descendent selector: #VerticalMenu li { ... }.

One last thing: The use of h4 elements seems wrong to me. Either this is a menu, then you shouldn't be using header elements at all, or the items in AccordionMenu are subheadlines and be using h5 instead.


Checking user permission, where permission is granted for specific EmployeeGroup that has self reference

No. I don't think your question is bad. It's only hard to answer on, since there are so many different ways to solve the problem your method addresses. And if they are better or not is kind of subjective. With that said here are some comment on your method:

Your method is too long and does too many things. I would recommend breaking it up into smaller method that does one thing; one that get the stuff from the database, one that checks the group permission and one that checks the parent group permission. Then the responsibility of the main method is to invoke the other if needed (and in what order).

I don't think the signature of the method is the best. Having int? emplooyeGroupID = null as a parameter is a clear indication that your method does two different major things; one if int? emplooyeGroupID is null and one if not. I would break it into two methods:

static bool CheckPermission(Session session, string right);
static bool CheckGroupPermission(Session session, string right, int emplooyeGroupID);

Then it will be up to the caller (client) to choose the right one. And since the caller knows if the emplooyeGroupID is null or not, the CheckPermission method don't need to "if" on it.

Why do you return true on the last line? I would definitely return false!

Otherwise you should be happy if the method does what you want it to.


Returning the last segment of a split string

I'm not entirely enthusiastic about either. The parts[parts.length - 1] using manual index lookup and subtraction may well take a moment to recognize, "Oh, this is getting the last element of the array". The second, using .reverse() followed by destructuring of the first item also could take a moment to think about before you understand what exactly it's doing.
As an alternative, consider using .pop() instead, I think it's more intuitive than both:
return someString
  .split('.')
  .pop();

The only (tiny) downside is that the above isn't functional, since it mutates the split array - but that's OK, since the array isn't being used anywhere else.
It's true that performance for something like this isn't really something to worry about if this is used in a larger project - what matters more is if it's easier to understand what the code is doing.
Remember that if something isn't immediately intuitive, that's what comments are for, though all of these cases are self-documenting enough that it's not needed.
Another way to make it easier to recognize what's going on would be to put this into a function with a descriptive name, such as getLastProperty (if the input is meant to show a path to a nested property lookup, for example - name it as appropriate for how it's meant to be used).


Getting columns from lines of uneven length

After you have tupls:

data = [(t[0], t[-3], t[-2], t[-1] for t in tupls] # Or use range...
print(list(zip(*data))

Gives:

[('8/5/15', '8/9/15'), ('custid', 'custid'), ('locid', 'otherlocid'), ('55.00', '79.00')]

So this:

testdata = """8/5/15 stuffidontneed custid locid 55.00
8/9/15 stuff i really dont need with extra spaces custid otherlocid 79.00"""
rows = testdata.split('\n')
tupls = [row.split(' ') for row in rows]
dates = [tupl[0] for tupl in tupls]
custids, locids, amounts = ([tupl[i] for tupl in tupls] for i in range (-3, 0))
print(dates, custids, locids, amounts)

Becomes:

testdata = """8/5/15 stuffidontneed custid locid 55.00
8/9/15 stuff i really dont need with extra spaces custid otherlocid 79.00"""
rows = testdata.split('\n')
tupls = [row.split(' ') for row in rows]
data = [(t[0], t[-3], t[-2], t[-1] for t in tupls] # Or use range...
print(list(zip(*data))


Using delegates to communicate between forms and networkcommunicator class

My suggestions:

If the NetworkCommunicator exists only once per application, you should create a singelton. Code sample:

    /// <summary>
    /// Provides a base class for singeltons.
    /// </summary>
    /// <typeparam name="T">The class that act as a singelton.</typeparam>
    public abstract class Singleton<T>
        where T : class
    {
        protected Singleton()
        {
        }

        /// <summary>
        /// Gets the singelton instance.
        /// </summary>
        public static T Instance
        {
            get { return Nested._instance; }
        }

        private sealed class Nested
        {
            /// <summary>
            /// Creates the nested instance class.
            /// </summary>
            ///
            /// <remarks>
            /// Explicit static constructor to tell the compiler
            //  not to mark type as beforefieldinit.
            /// </remarks>
            static Nested()
            {
                ConstructorInfo constructor = typeof (T).GetConstructor(Type.EmptyTypes) ??
                                              typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);

                if (constructor == null)
                    throw new InvalidOperationException("Class has no private nor public constructor");

                _instance = (T)constructor.Invoke(null);
            }

            internal static readonly T _instance;
        }
    }

If someone has any suggestion about my singelton implementation, let me know it..

The delegate makes the code more complex and violates the KISS OOP principle: Keep It Simple and Stupid. Make it as easy as possible first.


BuildQueryURL method

This method is in a very bad style. It's supposed to build a query url but you give it a name-value-collection that you modify it inside the method!

You should split it into two methods.

The first one should only UpdateParameters and the other one BuildQueryURL only build the url without modifying any other values and causing unexpected behaviour. I'd be really supprised if I used it and found that it actually changed the parameters too although it's name doesn't suggest anything like that.

Interval enum

If this is your enum then make the values exactly like the relative path so that you can just call .ToString() on it without a switch. If not then I'd use a dictionary to get rid of the switch.

Execute & GetWeather methods

Usually when we do somehting like this where we have an out argument and return a bool or another type of a result success indicator we name the method TryDoSomething so in your case the method should be called TryExecuteQuery and TryGetWeather


T extends Serializable

Why? There doesn't seem to be a good reason to do this.

throw new Exception("MyStack is Full, need to pop");

Your professor probably told you to do it like this, but it'd at the very least be an interesting exercise to see if you can resize the array to hold more, rather than letting it be full. It's not terribly difficult, either.

@SuppressWarnings("unchecked")

These are almost always unnecessary; you theoretically should be able to rewrite your code such that they're unnecessary.

However, if I'm remembering my Java correctly, that's not possible in this case, so it's better to eliminate the warning, so that the "real" ones are more visible.

this.myArray[this.arraySize++]

This code, though its behavior is well-defined, is not what you should be writing. Split it into two lines. The two statements -- the set and the increment -- already connected by being very nearly the sole contents of a method. Putting the increment in the brackets just makes it more likely that the increment won't be seen. I, for one, didn't see it until I took a closer look, because it appeared to be incorrect.

You don't get an award for fewer lines. Every second you don't need to spend re-reading your code later is a second you can use to implement new, cool features, and every second people reading your code don't spend on unclear syntax is a second they can use to find real bugs.

It's unfortunate that you can't remove the Class<T> passed in to the constructor, but that's the way it is, so good job for minimizing its impact.

Space and indent things consistently. This:

new MyStack<Integer>(Integer.class, 3);

is not consistent with this:

Array.newInstance(c , stackSize);

Now, your response to any of these could be "meh, it's a project for school, so I don't really care about that", to which my response is this:

School is supposed to teach you how to code well, in part by drilling how to do that into your head through practice. If you don't practice writing code well, you'll find yourself stuck in habits of writing code that works, but nobody can read after three months. If you practice writing code well -- as in, readable, clean code, not necessarily bug-free -- starting as soon as possible, you'll save yourself a lot of headache debugging later.


Convert ISO 8601 week to American-formatted date

convertDateToFormattedCalendarWeek = "error"
Debug.Print ("function convertDateToFormattedCalendarWeek called with invalid parameter mode " & mode)

Bad idea. A bad function call involving invalid parameters is a programming bug, and should be a serious run-time error that takes down the whole thing. By returning a String you're forcing the caller to systematically verify that it's not getting the "error" magic string literal.

The function has one job. If it can't do it, it should blow up: there's a run-time error specifically for this:

Err.Raise 5, "ConvertDateToFormattedCalendarWeek", _
             "Invalid 'mode' parameter value: " & mode

Run-time error 5 is essentially your ArgumentException. If I consume your function and pass an invalid parameter, I'm expecting that error to be raised.

But what's that mode anyway?

Public Function convertDateToFormattedCalendarWeek(input_date As Date, mode As Integer) As String

From the signature, I've no idea. [Seriously] consider using an enum instead:

Public Enum WeekFormattingMode
    WFM_AmericanStandard
    WFM_ISO8601
End Enum

And now your signature can be (note, member names should be PascalCase):

Public Function ConvertDateToFormattedCalendarWeek(input_date As Date, mode As WeekFormattingMode) As String

Now the caller gets auto-completion when calling the function, and has to work very hard to supply an invalid parameter value.

This also eliminates magic constants in your implementation, and replaces the otherwise needed comments, which makes the code more self-descriptive:

Select Case mode
    Case WFM_AmericanStandard
        'handle American Standard formatting

    Case WFM_ISO8601
        'handle ISO-8601 formatting

    Case Else
        Err.Raise 5, "ConvertDateToFormattedCalendarWeek", _
                     "An invalid 'mode' parameter was supplied"
End Select

The parameters are implicitly passed ByRef, but they're not assigned and the caller doesn't need to use them - they're really read-only inputs that the function needs in order to work with; such parameters should be passed ByVal.

I don't agree with all your naming conventions, but as long as it's consistent, it should be good. I like that you're not using the very commonly abused Systems Hungarian notation. Option Explicit shouldn't be part of a convention though - it should be mandatory for any VBA code that isn't toy code - and heck, even toy code should have it.

Since you're using underscores in identifiers, I need to mention that it's important that this convention isn't applied to member names, especially public ones. This is simple code and there's no harm, but in more complex object-oriented code, an underscore in a procedure name can mean code that can't compile: VBA is reserving the underscore for a very specific meaning in member names.

I like that your function is pure, and therefore easily testable. But where are the tests?

With Rubberduck (a free, open-source VBE add-in I'm working on with a bunch of fellow VBA reviewers) you could document your requirements - and have tests that you can run anytime you make a change, as simple as this:

Option Explicit
Option Private Module

'@TestModule
'@Folder("Tests")

Private Assert As New Rubberduck.AssertClass

'@TestMethod
Public Sub AmericanStandardOutputContainsSlashSpacer()
    On Error GoTo TestFail

    Const splitter As String = " / "
    Dim actual As String

    actual = ConvertDateToFormattedCalendarWeek(Date, WFM_AmericanStandard)
    Assert.IsTrue InStr(expected, splitter) > 0

TestExit:
    Exit Sub
TestFail:
    Assert.Fail "Test raised an error: #" & Err.Number & " - " & Err.Description
End Sub

And so on:

ISO standard weeks start on Monday
American standard weeks start on Sunday
...

Every part of the specifications should have at least one test that covers it. And then you'll want tests to document behavior for invalid inputs, too:

'@TestMethod
Public Sub RaisesErrorGivenInvalidMode()
    Const ExpectedError As Long = 5
    On Error GoTo TestFail

    Const InvalidMode As Long = -1
    If InvalidMode = WFM_AmericanStandard Or InvalidMode = WFM_ISO8601 Then
        Assert.Inconclusive "InvalidMode must be an invalid parameter value."
    End If

    Dim actual As String
    actual = ConvertDateToFormattedCalendarWeek(Now, InvalidMode)

Assert:
    Assert.Fail "Expected error was not raised."

TestExit:
    Exit Sub
TestFail:
    If Err.Number = ExpectedError Then
        Resume TestExit
    Else
        Resume Assert
    End If
End Sub

Arguably, that "mode" parameter indicates that the function is doing too many things. If you split it into FormatDateAmericanStandard and FormatDateISO8601 there would be no ambiguity whatsoever about how a date is formatted when you look at the calling code. Compare to:

foo = convertDateToFormattedCalendarWeek(someDate, 0)

Is foo formatted per the American standard or ISO-8601? The enum certainly helps, but then if I have to pick between this:

foo = ConvertDateToFormattedCalendarWeek(someDate, WFM_AmericanStandard)
bar = ConvertDateToFormattedCalendarWeek(someDate, WFM_ISO8601)

And this:

foo = FormatDateAmericanStandard(someDate)
bar = FormatDateISO8601(someDate)

I pick the latter without hesitation - note how it completely eliminates the whole discussion about raising an error vs. returning "error", and eliminates the need to test/document what happens given an invalid mode parameter. And it makes the code much more explicit and self-descriptive, too.

A note about the name: you're not "converting a date" - you're "formatting a date" per a specified standard; I'd make the function name start with FormatDate.


Constraint Programming: Map color problem

Your code looks good but I think you should have a look at PEP 8 which is the Style Guide for Python Code. Among other things, it says :

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

Also, you should probably add documentation especially as the solve method takes a parameter for no obvious reason. PEP 257 describes the Docstring Conventions.

Finally, the name you give to your variables and members can be quite confusing.

Your Territory class describes a territory by its name, its neighbours and its colors. The association from territory to color is valid only in the context of a MapColor. Thus, Territories could be described just by their name and neighbours. Instead of defining Australia with :

australia = { T:   Territory(T,   [V]                 ),
              WA:  Territory(WA,  [NT, SA]            ),
              NT:  Territory(NT,  [WA, Q, SA]         ),
              SA:  Territory(SA,  [WA, NT, Q, NSW, V] ),
              Q:   Territory(Q,   [NT, SA, NSW]       ),
              NSW: Territory(NSW, [Q, SA, V]          ),
              V:   Territory(V,   [SA, NSW, T]        ) }

one could get rid of the Territory class alltogether and remove the duplicated values by defining a mapping from name to containers of neighbours. Because neighbours do not need to be in a given order, a set will do the trick :

australia = { T:   {V                },
              WA:  {NT, SA           },
              NT:  {WA, Q, SA        },
              SA:  {WA, NT, Q, NSW, V},
              Q:   {NT, SA, NSW      },
              NSW: {Q, SA, V         },
              V:   {SA, NSW, T       } }

I also took this chance to add a function to check that the graph is properly defined :

def check_valid(graph):
    for node,nexts in graph.iteritems():
        assert(nexts) # no isolated node
        assert(node not in nexts) # # no node linked to itself
        for next in nexts:
            assert(next in graph and node in graph[next]) # A linked to B implies B linked to A

Then, in the MapColor class, you can add a dictionnary to map nodes to their colors (if any).

You don't need to store colors in your MapColor class as you don't reuse it afterward.
Also, the nodes member is not required neither.

The is_valid method can be rewritten in a more concise way using the function all.

The biggest problem in your code is probably the fact that most interesting function takes a parameter for no obvious reason. Easiest solution would be to make it a default parameter with value 0. A more interesting solution would be to try to understand when we want to stop which is when all nodes have been given a color. In order to do so, get the list of nodes with no color and consider we have a valid solution if this list is empty :

   uncolored_nodes = [n for n,c in self.node_colors.iteritems() if c is None]
    if not uncolored_nodes:
        print self.node_colors
        return True

Then, in order to know what is the next node to consider, just take the first of the list (at this stage, we know that the list cannot be empty):

    node = uncolored_nodes[0]

(This also makes obvious the fact that condition if self.map[var].color != None: (which would be written self.node_colors[node] is not None in my code) cannot be true by definition of node.

Once comments have been taken into account (except for the comments because I can't be bothered), the code looks like :

#!/usr/bin/python

def check_valid(graph):
    for node,nexts in graph.iteritems():
        assert(nexts) # no isolated node
        assert(node not in nexts) # # no node linked to itself
        for next in nexts:
            assert(next in graph and node in graph[next]) # A linked to B implies B linked to A

class MapColor:

    def __init__(self, graph, colors):
        check_valid(graph)
        self.graph = graph
        nodes = list(self.graph.keys())
        self.node_colors  = { node: None for node in nodes }
        self.domains = { node: set(colors) for node in nodes }

    def solve(self):
        uncolored_nodes = [n for n,c in self.node_colors.iteritems() if c is None]
        if not uncolored_nodes:
            print self.node_colors
            return True

        node = uncolored_nodes[0]
        print 'domain for '  + node + ': ' + str(self.domains[node])
        for color in self.domains[node]:
            if all(color != self.node_colors[n] for n in self.graph[node]):
                self.set_color(node, color)
                self.remove_from_domains(node, color)

                if self.solve():
                    return True

                self.set_color(node, None)
                self.add_to_domains(node, color)

        return False

    def set_color(self, key, color):
        self.node_colors[key] = color

    def remove_from_domains(self, key, color):
        for node in self.graph[key]:
            if color in self.domains[node]:
                self.domains[node].remove(color)

    def add_to_domains(self, key, color):
        for node in self.graph[key]:
            self.domains[node].add(color)

WA  = 'western australia'
NT  = 'northwest territories'
SA  = 'southern australia'
Q   = 'queensland'
NSW = 'new south wales'
V   = 'victoria'
T   = 'tasmania'

colors    = {'r', 'g', 'b'}

australia = { T:   {V                },
              WA:  {NT, SA           },
              NT:  {WA, Q, SA        },
              SA:  {WA, NT, Q, NSW, V},
              Q:   {NT, SA, NSW      },
              NSW: {Q, SA, V         },
              V:   {SA, NSW, T       } }

problem = MapColor(australia, colors)

problem.solve()

Once all of this has been done, one can notice that the node_colors and domains contain somewhat duplicated information : a node n has color c if and only if domains[n] == {c}. I have no time to get rid of node_colors but that would be my next suggestion. Also, there might be a problem with the way you add/remove colors because when calling self.add_to_domains(node, color) we might re-add a color that has been removed at an earlier stage. I am not able to find an example right now but it might be something to consider. Please let me know if you think I am wrong.

Problem in your code (and in mine) : trying to make the test case a bit more interesting (at the moment, your example does not encounter any problem), I've discovered a problem.

Indeed, I was adding Queensland as a neighboor of Victoria (which is still possible in a planar graph if the Sunshine State decided to invade the West Coast of NSW) and I got the following error :

Traceback (most recent call last):
  File "./colors_original.py", line 99, in <module>
    problem.solve(0)
  File "./colors_original.py", line 43, in solve
    if self.solve(i + 1):
  File "./colors_original.py", line 43, in solve
    if self.solve(i + 1):
  File "./colors_original.py", line 36, in solve
    for color in self.domains[var]:
RuntimeError: Set changed size during iteration

Before trying to go for better perf, I think you should try to make this correct. Because maintaining a consistent state whilst calling recursive method can be quite hard, I guess you should try to make things as simple as possible. I'll try to update this answer if I think of anything interesting but it is quite unlikely.


Rotate every letter in string by K places

if the only thing you need to encrypt in the string are the letters, you can be more concise by using only one loop doing something like:

if c >= 'a' && c <= 'z' {
    a = (((c-'a')+K)%26)+'a'
} else if c>= 'A' && c <= 'Z' {
    a = (((c-'A')+K)%26)+'A'
} else {
    a = c
}

with c being the char from the original string and a the char to add to the encrypted string.


Use map get key contains value, to test if a given key-value-pair is already part of a Map.

Your solution is extremely inefficient, because you iterate through the entire Map (with collect) just to find one value. get returns an Option which can be checked for the containing value.


Counting pairs that have a given difference in Java

From a review of your code, I see that you loop over your input in a nested for loop. This is actually not required to solve the problem. Instead, create one hashset for every number in your numbers array, and another hashset for every number in numbers + k. Then we only have to check for intersections.

This should take your \$O(n^2)\$ algorithm and turn it into a nicer \$O(n)\$. Here's my suggested code (note that I included an inner class to store the pairs, but you could use builtins to solve it too:

private static class Pair {
    public int a;
    public int b;
    public Pair(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public String toString() {
        return "("+a+","+b+")";
    }
}

public static List<Pair> getPairsFast(int k, List<Integer> numbers) {
    HashSet<Integer> hLow = new HashSet<>();
    HashSet<Integer> hHigh = new HashSet<>();
    List<Pair> ret = new ArrayList<>();
    for (int i : numbers) {
        hLow.add(i);
        hHigh.add(i+k);
    }
    for (int i : hHigh) {
        if (hLow.contains(i)) {
            ret.add(new Pair(i-k, i));
        }
    }
    return ret;
}

From some testing, it indeed seems to perform better the larger the input is, and it is >400 times faster for an input of size \$10^5\$.


Determine whether any permutation of a given array exists such that the sum of all subarrays of length K are equal

Use the collections.Counter instead of keeping a count yourself.

When you have counted all the elements from the list, check if any of their counts is not a factor of \$ N \$ and return False.

Therefore:

from collections import Counter

def check(nums, n, k):
    if n == k:
        return True
    counts = Counter(nums)
    if len(counts) > k:
        return False
    return all((n % x == 0 for x in counts.values()))


Classifying and counting database entries using Scala map and flatMap

Let me start with out-of-the-box solution I would use if I were and after that we'll discuss your code. I assume df is equivalent to the following structure:

val df = Seq(
  (1, "John", "S1", "green"), (2, "Shaun", "S2", "red"),
  (3, "Shaun", "S2", "green"), (4, "Shaun", "S2", "green"),
  (5, "John", "S1", "yellow")
).toDF("id", "name", "eid", "color")

All you really need to achieve desired output is pivot:

df.groupBy("name", "eid").pivot("color").count().na.fill(0).show

// +-----+---+-----+---+------+
// | name|eid|green|red|yellow|
// +-----+---+-----+---+------+
// |Shaun| S2|    2|  1|     0|
// | John| S1|    1|  0|     1|
// +-----+---+-----+---+------+

About your code:

Don't fetch more data from a DataFrame than you really need. Once you convert DataFrame you don't longer benefit from early projections, selections and other Catalyst optimizations.

It means you have to fetch all the data from external source (like a database) or off-heap storage even if downstream processing requires only a small fraction of it. In other words project early:

df.select($"name", $"eid", $"color").rdd.map { ... }

Avoid dealing with RDD[Row]. It is like a Seq[Any] - nothing you really want in your code. Instead you can use Dataset encoders:

df.select($"name", $"eid", $"color").as[(String, String, String)].rdd.map {
  ...
}

Never use list concatenation for reduction. Since List.++ is O(N) operation and you apply it in a loop overall complexity is roughly O(N2). If you really want to group data use groupByKey.
But don't group if operation can be expressed using reduceByKey with a truly reducing (requiring roughly constant memory) function.

There many ways you can approach this for example with aggregateByKey (note that I intentionally use mutable buffer):

import scala.collection.mutable.Map

val pairs = df
  .select($"name", $"eid", $"color")
  .as[(String, String, String)]
  .rdd.map { case (name, eid, color) => ((name, eid), color) }

def seqOp(acc: Map[String, Long], x: String) = {
  acc(x) = 1L + acc.getOrElse(x, 0L)
  acc
}

def mergeOp(acc1: Map[String, Long], acc2: Map[String, Long]) = {
  acc2.foreach { case (k, v) => acc1(k) = v + acc1.getOrElse(k, 0L) }
  acc1
}

pairs
  .aggregateByKey(Map.empty[String, Long])(seqOp, mergeOp)
  .map {
    case ((name, eid), vs ) =>
      (name, eid, vs.get("red"), vs.get("green"), vs.get("yellow"))
  }.toDF("name", "eid", "red", "green", "yellow")


Code to change the size of the fields based on that 2 fields are optional inside a contact form

I think your current code looks pretty reasonable. All the logic you're typing out is required, and it's quite readable as-is. There are a few tweaks you can consider, but there could well be different opinions on whether it makes the code more elegant or not.
Array search You initially save into 2 variables whether a couple particular properties exist in the array of objects. You can make that a bit nicer by first mapping to an array of .names, then using .includes instead:
const configNames = fieldsConfig.map(config => config.name);
const hasTime = configNames.includes('preferredContactHours');
const hasContactType = configNames.includes('preferredContactWay');

Abstract into a function Your whole code snippet runs for the purpose of figuring out the size to use. Rather than having this block among whatever else may exist on that level, and rather than conditionally reassigning size in a bunch of places, you might consider a function that calculates the size instead:
const size = getSize();

(This also lets you define size with const, which is great)
Save the comparisons into variables Rather than performing the same test multiple times, you can save them into variables first, it'll help a bit:
const preferredContactWay = name === 'preferredContactWay';
const preferredContactHours = name === 'preferredContactHours';

Group the conditions that result in the same size (just an option, you may or may not like how it looks):
const getSize = () => {
  if (!useMediaQuery(theme.breakpoints.up('sm'))) {
    return 12;
  }
  const configNames = fieldsConfig.map(config => config.name);
  const hasTime = configNames.includes('preferredContactHours');
  const hasContactType = configNames.includes('preferredContactWay');

  if (name === 'phone' && (!hasTime || !hasContactType)) return 7;

  const preferredContactWay = name === 'preferredContactWay';
  const preferredContactHours = name === 'preferredContactHours';

  if (
    (preferredContactWay && hasTime) ||
    (preferredContactHours && hasContactType)
  ) {
    return 6;
  }
  else if (
    (preferredContactWay && !hasTime) ||
    (preferredContactHours && !hasContactType)
  ) {
    return 5;
  }
  return 12;
}

RE: comment, to call useMediaQuery in the caller of getSize, either do:
const size = useMediaQuery(theme.breakpoints.up('sm') ? 12 : getSize();

or
const size = getSize(useMediaQuery(theme.breakpoints.up('sm'));

altering the body of getSize as needed to check the parameter.


What Data Annotations need to be shared/different between my Model & ViewModel to keep seperation of concerns?

I'm using localized strings from my views/resources.resx in my Model
  for Display Attributes, does this violate the separation of concerns
  since it's a resource in my views folder intended for views?

I would probably say yes.  You are tying UI concerns in your business models.  Why does your model even care about the text that is used to display it?  It should be more concerned with buiseness rules and performing buiseness operations I think.  Let your UI layer/layers deal with presenting it to the user.

  Do I need a ViewModel for my Model to keep separation of concerns? And
  if so, which Annotations need to go on my model's properties, and
  which need to go on the ViewModel properties?

No I don't think you necessarilly need a viewmodel and there is plenty of debate on this on the internet.  However I personally like the viewmodel approach as it provides the flexibility of adding any UI specified fields I would like without the overhead of my view being tied directly to the buiseness model.  Of course this means also that you now have to have the rules copied twice like you mentioned.  However if you were using jquery validation this would be the case anyway (or so I believe).


List directories, subdirectories and files, while ignoring some dirs

You are already modifiyin the list of directories, so that should be enough. But your exclude includes the full path, so your check in the list comprehension does not actually filter the excluded directories, you only do that in the for loop below when already having descended into those excluded directories (wasting time).

So, this should work:

from os import walk, path

exclude = {'./dir1/foo'}

for root, dirs, files in walk('.'):
    if exclude is not None:
        dirs[:] = [d for d in dirs if path.join(root, d) not in exclude]
    for name in files:
        print path.join(root, name)

Note that exclude needs to contain paths starting with the starting point of os.walk, so in this case ..

I also made exclude a set (\$\mathcal{O}(1)\$ in lookup), used the fact that topdown=True by default and used is not instead of != for comparison to None.

If you want to instead exclude folder names (regardless of their position in the directory tree), you can do that as well like this:

from os import walk, path

exclude = {'foo'}

for root, dirs, files in walk('.'):
    if exclude is not None:
        dirs[:] = [d for d in dirs if d not in exclude]
    for name in files:
        print path.join(root, name)

What is not possible with either of these two approaches is to include foo only in sub-directories of dir1, like in your example. However, I think this is more consistent behaviour, so you should choose one of the two, IMO.

As a last point, you should probably switch to Python 3 sooner rather than later if at all possible, because support for Python 2 will end in a bit more than a year (at the time of writing this).


Single Linked List - Improvements - 1 - not complete

/* C++ Version - lnode, lnode_reverse, lnode_push, lnode_print, lnode_count
   I need node_type turned into a templated class..How does one do this?
*/
typedef struct node_type
  {
  int data;
  struct node_type* next;
  } lnode_type;

Turning it into a template is pretty straightforward:

template <class T>
class node_type {
   T data;
   node_type *next;
};

Note that the typedef isn't really necessary (or desirable) in C++. You normally just want to use class whatever, and then the body of the class definition. This makes whatever usable as a name by itself, just about like the typedef would in C.

There's one other thing we probably want to do though: the whole basic idea of a linked-list node is really just an implementation detail of the linked list, so we really want to make the node type a nested class inside of the linked-list class:

template <class T>
class sl_list {

    struct node {
        T data;
        node *next;
    } head;

public:
    // Other stuff here.
};

From there, we want to write the functions that work with the data type to use T instead of int. For example, instead of your push(int), you might write something like this:

void push(T data) {
  ++count; // prefer pre-increment when you don't need the old value.
  node* newNode = new node;
  newNode->data = data;
  newNode->next = head;
  head = newNode;
}

We might prefer to add a ctor to the node class/struct, something like this:

node(T data, node *next = NULL) : data(data), next(next) {}

With that, push becomes something like this:

void push(T data) {
    node *newNode = new node(data, head);
    ++count;
    head = newNode;
}

[Edit2: Note that, as recommended by @LokiAstari, I've also moved the ++count to after allocating the new node. This way if the attempted allocation fails (and new throws an exception), count will not be incremented, so it retains the correct values. If and only if the allocation succeeds, it's incremented to reflect the new node having been added to the list. ]

[Edit: and node would look roughly like this:

    struct node {
        T data;
        node *next;

        node(T data, node *next = NULL) : data(data), next(next) {}
    } head;

]


What standard should I use for the naming of my MVC controller services?

I don't think it matters as long as you are consistent. I personally prefer:  _{servicename}Service format. ex. _referenceService

public class ContentsController : BaseController {
        private IContentService _contentService;
        private IPageService _pageService;
        private IReferenceService _referenceService;
        private ISequenceService _seqService;

        public ContentsController(
            IContentService contentService,
            IPageService pageService,
            IReferenceService referenceService,
            ISequenceService sequenceService) {
            this._contentService = contentService;
            this._pageService = pageService;
            this._referenceService = referenceService;
            this._seqService = sequenceService;
        }


Note class for managing information on various musical notes

Although you put the three classes into one file, they are already three classes. So you already split the responsibility. Translating a float to a length is one "responsibility" and translating the pitch to a name is another. Seen from this angle everything is fine.

SRP is a heuristic for good OO code. You won't go straight to hell if your class does two things. But if your class does 20 things you should consider a refactoring.

If you have the feeling that your code is not readable or your file is too long, just extract the inner enum to standalone enum. In most cases it is no difference if you have an inner class/enum or a real one, so you should prefer the more readable solution.

In addition to that, I would store the length as the enum at the note and translate it once in the setter (reused in the constructor) instead doing it every time in the getter. I'm also in doubt if I would offer an interface with a integer length getter and the enum length getter. Usually you want to force the caller to use the enum object, I guess.

You should try to use this and the getters in a consistent way.

Have you considered all the nasty pitfalls in using the float type? If you don't want to do any math I would prefer String, otherwise you might want to think about using BigDecimal.


The nice thing about the code below is that if there are ever more inputs you only need to add one line for each, though as has been mentioned in the comments the way you do your html and css can decrease the size of your javascript.

$(function() {
    var elements = {
        "1" : "#input",
        "2" : "#textarea",
        "3" : "#option"
    };
    var show_selected = function(selected) {
        for (var key in elements)
            $(elements[key]).toggle(selected === key);
    };
    //Hide elements
    show_selected();

    //Show element based on selection
    $('#input_type').change(function(){    // use class or use $('select')
        show_selected($(this).val());
    });
});

below is an example where your html can reduce your javascript.

<textarea class="input_type" id="textarea"></textarea>
<input class="input_type" id="input" />
<select class="input_type" id="option">
    <option>Option 1</option>
    <option>Option 2</option>
</select>
<select id="input_type">
    <option>-</option>
    <option>input</option>
    <option>textarea</option>
    <option>option</option>
</select>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function() {
    //Hide elements
    $(".input_type").hide();

    //Show element based on selection
    $('#input_type').change(function(){    // use class or use $('select')
        $(".input_type").hide();
        $("#" + $(this).val()).show();
    });
});
</script>


Program to automate clicking on the new button on a chat website until the username matches certain conditions

Your third part is wrong, I think.

nonCompatible = 'female' not in name

will only run against the value of name at the time of execution, so nonCompatible will end up either True or False, and won't change unless you reset it elsewhere in the while loop.  You may want to either inline it:

while 'female' not in name:
    ...

or abstract it:

def nonCompatible(nym):
    return 'female' not in nym

while nonCompatible(name):
    ...


Avoiding RequireJS circular dependencies

There are few ways to solve your problem with Backbone.js + Require.js and executing functions or changing routes from view.

1. Using Backbone.Router

Here is approach I've used multiple times:

'use strict';

// Your view --------------
define([
    'jquery'
    'backbone'
    'common/views/view',
    'common/helpers/misc'
], function ($, Backbone, View, Misc) {

    var ZineItemView = View.extend({
        ...
        showZine: function (e) {
          if (!Misc.shouldHandleClick(e)) {
            return;
          }
          // Pass all control from view to the router,
          // see http://stackoverflow.com/a/20311253/1363799
          Backbone.history.navigate('yourUrl_to_zine');
        }
    });

    return ZineItemView;
});

// Main block --------------
require([
    'jquery'
    'backbone',
    'app',
    'ZineItemView'
], function($, Backbone, App, ZineItemView) {
    ...

    var app = new App();

    var zineItemView = new ZineItemView({...});

    // Router way
    var router = Backbone.Router.extend({
      routes: {
        "yourUrl_to_zine": "showZine"
      },
      showZine: function() {
            // Here you gave access to zineItemView.model and zineItemView.model.id
            app.presenter.showZine({
                zine: zineItemView.model,
                // I think next row becames obsolete
                route: app.router.routeToZineTrending(zineItemView.model.id)
            });
        }
    });
});

2. Event-driven approach

'use strict';

// Your view --------------
define([
    'jquery',
    'backbone',
    'common/views/view',
    'common/helpers/misc'
], function ($, Backbone, View, Misc) {

    var ZineItemView = View.extend({
        ...
        showZine: function (e) {
          if (!Misc.shouldHandleClick(e)) {
            return;
          }

          var view = this;

          // Trigger global event with desired parameters
          $(window).trigger('showZine.App', {
            zine: view.model,
            modelId: view.model.id // probably it's obsolete, because you can get it from zine property
          });
        }
    });

    return ZineItemView;
});

// Somewhere in app block --------------
// lodash is a dependency, because we use bind method
var App = {
    initialize: function() {
        $(window).on('showZine.App', _.bind(this.presenter.showZine, this) );
    },
    presenter: {
        showZine: function(event, paramsObj) {
            // Here you have paramsObj,
            // with paramsObj.zine = zineItemView.model
            // and paramsObj.modelId = zineItemView.model.id

            // Call app.router.routeToZineTrending from here, but be aware about value of `this` and `app` variables
        }
    }
};

3. Syntax of module defining (optional)

It preferentual, but seems to be a standart (it's easier to see dependencies):

'use strict';

define([
    'common/views/view',
    'common/helpers/misc',
    'app'
], function (View, Misc, app) {

    var ZineItemView = View.extend({
        ...
    });

    return ZineItemView;
});


Bash script to monitor Webserver php script

#!/bin/bash

Minor, still good to know, this is not portable, f.e. BSDs will choke on it. This might not be an issue if you only intent to use it on Linux, but if you ever release script into the wild, you should consider using a portable shebang line.

#!/usr/bin/env bash

if [[ -z "$1" ]] # check if script arguement exists
then

I'm a friend of the one-line-style, but that is for sure a pure personal preference.

if [[ -z "$1" ]]; then # check if script arguement exists

a=$(./IDscript "server");

From the context of this I can say two things:

that variable needs a better name
that script needs a better name

It is not obvious what the script does and neither what the variable will hold.

a=$(./IDscript "server");

In a shell script, there's no need to close every line with a semicolon. You can do it, but it's not necessary.

lenA=$(expr length "$a");

If you're going to use Bash, you can also use Bash syntax:

lenA=${#a}

Or shortened to:

if [ ${#a} -eq 0 ] #check length of A is empty
then

if [[ -z "$1" ]]

What I made a habit out of in the last time is extracting arguments into named variables so that the script is easier to read.

webAddress=$1

if [[ -z "$webAddress" ]]
...
testURL=$webAddress"/checkError?which=IDError&rand="$r;

This is of course not always useful, but pretty neat if you're going to use $1 in multiple places, as the script becomes easier to read.

echo -e "\n";

This can be shortened.

echo


I like all of Ev. Kounis' answer, so I'll add some higher level details.

Let it be truth-y

Right now you aren't strictly requiring func to return True or False, just something truth-y or false-y. This is fine, and Pythonic. I think you would benefit from pointing that out in a docstring (which you should also write). Additionally, it may be worthwhile to return the actual value of func(*func_args) instead of True or False; this way you can actually get a value from the function if you wanted to take advantage of the truth-yness of the value.

Better kwargs support

You also don't allow any keyword arguments to be passed to the function - the function might support them, so you should to. I would promote the two keyword arguments you pull out of kwargs to explicit keyword arguments, with appropriate defaults (5 in your case).

Exceptions

It's weird to me that this function does have any concept of retrying after exceptions. I wouldn't want you to do something like this, for what I hope are obvious reasons

for _ in range(retry_count):
    try:
        if func(*func_args):
            return True
    except:
        pass
    log.debug("wating for %s seconds before retrying again")
    sleep delay)

However, in many cases I suspect you would know what exceptions you might expect (for example, a network timeout or connectivity blip) and that you might want to be handled by the retrying framework. To this end, I think something like this could be nice:

def retry(func, *args, retry_count=5, delay=5, allowed_exceptions=(), **kwargs):
    for _ in range(retry_count):
        try:
            result = func(*args, **kwargs)
            if result: return result
        except allowed_exceptions as e:
            pass

This obviously isn't a complete implementation; I left out some of the other pieces you have, and it behaves oddly if it fails on the last iteration, but it should be enough to start.

Fancy stuff

I think we could also get more value from this if it was a decorator. Then consumers of a function don't even need to know if they want it to retry or not; they just call their function and see that it works, and whether or not it was retried becomes irrelevant. Don't forget to use functools.wraps to preserve metadata.

import functools

def retry(retry_count=5, delay=5, allowed_exceptions=()):
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            for _ in range(retry_count):
                # everything in here would be the same

        return wrapper
    return decorator

Then you can enable retrying for everyone, like so:

@retry(retry_count=5, delay=5)
def is_user_exist(username):
    try:
        pwd.getpwnam(username)
        log.info("User %s exist" % username)
        return True
    except KeyError:
        log.exception("User %s does not exist." % username)
        return False

Really fancy stuff

Why block when you're waiting? You could be doing so much more (this is for Python 3.5 and above) using asyncio.  There isn't built-in support for this before that, but I know there are asynchronous frameworks that should be able to accomplish the same task.

By awaiting an asynchronous function that just runs for n seconds, you achieve the same goal but allow other asynchronous functions to do work while you're just waiting. Note that depending on the event loop you might end up waiting for slightly more or less time.

I also cleaned up the issues I mentioned about handling exceptions; it now always returns the result of the function if it has one, and it'll re-raise the exception without losing any traceback if there was one. That also uses a Python 3 only feature; I've left a comment for how to do it in Python 2.

Note, I'm not as familiar with asyncio as I never got to do any serious dev there, so I might not have this piece of code exactly correct; the theory should be sound though.

import functools
import asyncio

def retry(retry_count=5, delay=5, allowed_exceptions=()):
    def decorator(f):
        @functools.wraps(f)
        async def wrapper(*args, **kwargs):
            result = None
            last_exception = None
            for _ in range(retry_count):
                try:
                    result = func(*func_args, **kwargs)
                    if result: return result
                except allowed_exceptions as e:
                    last_exception = e
                log.debug("Waiting for %s seconds before retrying again")
                await asyncio.sleep(delay)

            if last_exception is not None:
                raise type(last_exception) from last_exception
                # Python 2
                # import sys
                # raise type(last_exception), type(last_exception)(last_exception), sys.exc_info()[2]

            return result

        return wrapper
    return decorator


Function to generate all subsets of size n

Readability is a big factor in programming when it comes to maintaining the code by yourself or some other developer.
Readability can be improved by using standards which other developers expecting to see. Therefor some guidelines had been created like the .NET Naming Guidelines to name things like classes, properties, variables and parameters. Based on these guidlines variables should be named using camelCase casing instead of snake_case casing.

Omitting braces {} can lead to hidden and therfor hard to find bugs. i would like to encourage you to always use them.

That beeing said I will first focus on one part of your code...no, on two parts of your code but both are related.

while (indices[0] <= Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + 0)) + 1)

and

if (indices[i] > Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + i)) + 1)

but lets focus on the right part of the first line

Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + 0)) + 1

using simple math we can shorten this by removing the first () like so

Set.Length - 1 - (Set.Length - 1 - Set.Length + 1 + indices.Length - 0) + 1

and by removing the remaining () like so

Set.Length - 1 - Set.Length + 1 + Set.Length - 1 - indices.Length + 0 + 1

we get

Set.Length - indices.Length + 0

which is just

Set.Length - nElement + 0

which makes the while much more readable like so

int maxValueOfFirstIndex = Set.Length - nElement;

while (indices[0] <= maxValueOfFirstIndex)
{

}

which can be applied to the former if condition like so

if (indices[i] > maxValueOfFirstIndex  + i)
{

}

but nElement isn't as expressive as it could so numberOfItems could be a better name.

The T[] temp_arr isn't used in a useful way. You can safely remove it.
The check for nElement < 1 whouldn't throw an Exception but an ArgumentOutOfRangeException.
because variables should be declared as near as possible to their usage you should move the declaration of T[] arr inside the while.
by using Enumerable.Repeat().Select().ToArray() you can simplify the creation of indeces[] like so

int[] indices = Enumerable.Repeat(0, nElement).Select((s, d) => s + d).ToArray();

creating the T[] arr by a method would clean the main method as well
using the var type instead of concrete types can help if you later need to refactor to use a different type. And its shorter to write hence easier to read, at least if the type can be seen clearly from the right hand side of the assignment.

Applying the mentioned points will lead to

public List<T[]> GenerateCoupleOf(int numberOfItems)
{
    if (numberOfItems < 1)
    {
        throw new ArgumentOutOfRangeException("numberOfItems", "Value must be greater than 0");
    }

    var tr = new List<T[]>();

    var indices = Enumerable.Repeat(0, numberOfItems).Select((s, d) => s + d).ToArray();

    var maxValueOfFirstIndex = Set.Length - numberOfItems;

    while (indices[0] <= maxValueOfFirstIndex)
    {

        T[] arr = CreateArrayByIndices(indices, numberOfItems);

        tr.Add(arr);

        indices[indices.Length - 1]++;

        for (var i = indices.Length - 1; i > 0; i--)
        {
            if (indices[i] > maxValueOfFirstIndex + i)
            {
                indices[i - 1]++;
                for (var j = i; j < indices.Length; j++)
                {
                    indices[j] = indices[j - 1] + 1;
                }
            }
        }
    }

    return tr;
}
private T[] CreateArrayByIndices(int[] indices, int numberOfItems)
{

    var arr = new T[numberOfItems];

    for (int i = 0; i < indices.Length; i++)
    {
        arr[i] = Set[indices[i]];
    }
    return arr;
}


Redirecting mobile devices to another page best practise

The global task of mobile detection aside, just in regard of the current implementation.

Every time you see a duplicated code, there is a room for the improvement.

$mobile = false;
$mob_agents = ["iPhone","Android","webOS","BlackBerry","iPod","iPad"];
foreach ($mob_agents as $marker) {
if (strpos($_SERVER['HTTP_USER_AGENT'], $marker) !== FALSE) {
    $mobile = true;
    break;
}

now you can use a $mobile variable to test whether it's a movile client or not

A more sophisticated version would involve basic regular expressions- something like this:

$pattern = "/iPhone|Android|webOS|BlackBerry|iPod|iPad/";
$mobile = preg_match($pattern, $_SERVER['HTTP_USER_AGENT']);


I setup nodes.size() to return 744.
This then forces all 553536 to be read from the file.

When I run your code it completes in 3.8 seconds (with -O3 it takes 2.5 seconds).

If I update the code to reserve the appropriate amount of space in each vector we can reduce the time it takes to: 3.3 seconds (with -O3 2.2 seconds).

So for the 5 minute figure you are quoting there must be some other error in your code.

Comments on your code:

Pass no-mutable parameters by cost reference (to avoid the copy).

void Level::PopulatePathVectors(string pathTable)

Add lines to reserve the appropriate space in each vector. This will prevent multiple re-allocations of the vector while you read. This is important when you have a triply nested vector.

    pathLookupVectors.push_back(vector<vector<int> >());
    pathLookupVectors.reserve(nodes.size());                // Add this line

    for (unsigned int i = 0; i < nodes.size(); i++)
    {
        pathLookupVectors.push_back(vector<vector<int>>());
        pathLookupVectors.back().reserve(nodes.size())      // Add this line

No Need to manually close the file.
see https://stackoverflow.com/q/748014/14065
Implementation using fstream failed evaluation

myFile.close();


You don't present the entire code for the class here, but the usage of self and the doctests within the docstring indicates that you are actually using a class. As such my first order would be that in the initialisation of the class you always create the _items list, which would remove the need to check whether there are elements or not when adding elements.

To use i = len(self._items) to terminate the loop is a hackish solution. It would be better to use break instead. But while and for (and actually try ... except) allows for the usage of else which can help out in this particular case. In short, if the loop terminates ordinarily, the else part is executed, if you break out of it, it'll not be executed.

In stead of doing the while i < len(self._items) loop, which requires calculating the length multiple times, and doesn't look to Pythonic, I would suggest using for i, item in enumerate(self._items). This loop construct loops over all the elements (if any) and gives the index of the current element (due to the use of enumerate()).

Lastly, naming the method additems() when you only add one element is misleading and not following standards. A better name would be add_item().

This leads to the following code:

class PriorityQueue(object):

    def __init__(self):
        self._items = []

    def add_item(self, new_item):
        """Add items into queue at correct place."""

        for i, item in enumerate(self._items):
            if new_item < item:
                self._items.insert(i, new_item)
                break
        else:
            self._items.append(new_item)

def main():
    pq = PriorityQueue()
    pq.add_item("yellow")
    pq.add_item("blue")
    pq.add_item("red")
    pq.add_item("green")

    print(pq._items)

if __name__ == '__main__':
    main()

I'm sorry that the environment I tested this in doesn't support doctests, but this does output the correct list of ['blue', 'green', 'red', 'yellow'].


Representing a Java Swing containment hierarchy in Haskell

EDIT: Faithfully representing OO semantics in Haskell is currently impossible. In particular, method resolution can be simulated (but not easily, and not quite faithfully) via type classes and instances. This paper is very informative about current best practice, and possible future evolution.

Here is one possibility, which is similar to your first solution:

data ComponentClass a
    = ComponentClass {
        ...
        , comSubclass :: a
        ...
        }
type Component = ComponentClass ()

data ButtonClass a
    = ButtonClass {
        , buttonText :: Text
        , btSubclass :: a
        ...
        }
type Button = ComponentClass (ButtonClass ())

This is what I would do if I thought a simple hierachy fit my problem
domain well (but not necessarily to mirror the OO in another language).
However, this strategy does not work well if you need to track deep
hierarchies, or multiple superclasses (such as in Python).

Another disadvantage is that you cannot deconstruct an arbitrary
ComponentClass a into its subtype a. You can only do this if you
know the type of a in advance. However, you could use dynamic typing
to fix this issue, such as via Typable.

Note that you could also represent the hierachy in the up direction as well:

data ButtonClass a
    = ButtonClass {
          btText :: Text
        , btSuperClass :: a
        }
type Button = ButtonClass ComponentClass

You could then build each object "down the class hierarchy" until you
discovered the most concrete type to wrap it up in.

Also note that Gtk2Hs uses a
typeclassing strategy similar to your second one to represent the class
hierachy of Gtk. Perhaps a look at its source code would be edicational,
or even just browsing its documentation on Hackage.

Finally, the Exception hierachy implemented in GHC is quite interesting, though I don't think it would help you as much as either of the above---it's quite flat by comparison.


Implement C++11 multipart sending without copying to a single buffer

Use namespace if you want a namespace

You use your struct only as a way to have merge and split not in the global namespace (and inlined). That's not necessary. We can just use a namespace:

namespace MultipartSplitMerge {
    ...
}

Don't use define for compile-time constants

You define PADDING, but you never undefine it. It's a common word in code, so it's possible that you accidentally break something. Furthermore, it's not in the same namespace as merge and split, as the preprocessor does not care about namespaces.

Instead, use a static constexpr size_t:

static constexpr size_t PADDING = 8;

This has the nice side-effect that PADDING has now a type. The compiler can now warn you when you try to compare it to other, signed types.

Prefer references instead of pointers

Not only are they easier to use, they also are harder to get wrong.

Use const on call-by-reference/-pointer arguments that are not changed

You never change s1, s2 and s3, yet you didn't use const. We could have changed their values accidentally. A const will prevent this:

inline std::string merge(const std::string& s1, const std::string& s2, const std::string& s3) {
    const std::string size_1 = std::to_string(s1.size());
    const std::string size_2 = std::to_string(s2.size());
    const std::string padded_size_1 = std::string(PADDING - size_1.length(), '0') + size_1;
    const std::string padded_size_2 = std::string(PADDING - size_2.length(), '0') + size_2;
    const std::string ret_str(padded_size_1 + padded_size_2 + s1 + s2 + s3);
    return ret_str; // Add the size of each piece
}

inline void split(const std::string& s, std::string &o1, std::string &o2, std::string &o3) {
    const unsigned int size_1 = std::stoi(s.substr(0, PADDING));
    const unsigned int size_2 = std::stoi(s.substr(PADDING, PADDING));
    o1 = s.substr(2 * PADDING, size_1);
    o2 = s.substr(2 * PADDING + size_1, size_2);
    o3 = s.substr(2 * PADDING + size_1 + size_2);
}

Note that all this inline annotations are only necessary if your functions will be in a header.

Don't repeat yourself

You pad your string, but it's a) hard to get and b) repetitive. Write a function to get rid of the duplicate logic:

inline std::string pad(size_t size, char padding, const std::string& original) {
    assert(size >= original.size());
    return std::string(size - original.size(), padding) + original;
}

inline std::string pad_size(const std::string& original) {
    return pad(PADDING, '0', std::to_string(original.size()));
}

If you find an optimization for pad or pad_size, merge gets optimized for free. And it gets a lot shorter:

inline std::string merge(const std::string& s1, const std::string& s2, const std::string& s3) {
    return pad_size(s1) + pad_size(s2) + s1 + s2 + s3;
}

All code at once

Now let us inspect the reviewed and somewhat rewritten code:

namespace MultipartSplitMerge {
static constexpr size_t FIXED_FIELD_LENGTH = 8;

// Optional `detail' namespace; shows a user that `pad' and `pad_size'
// are implementation details. Only important in a header-only
// library
namespace detail {
inline std::string pad(size_t size, char padding, const std::string &original) {
    assert(size >= original.size());
    return std::string(size - original.size(), padding) + original;
}

inline std::string pad_size(const std::string & original) {
    return pad(FIXED_FIELD_LENGTH, '0', std::to_string(original.size()));
}
} // namespace detail

inline std::string merge(const std::string& s1, const std::string& s2, const std::string& s3) {
    return detail::pad_size(s1) + detail::pad_size(s2) + s1 + s2 + s3;
}

inline void split(const std::string& s, std::string& o1, std::string& o2, std::string& o3) {
    const unsigned int size_1 = std::stoi(s.substr(0, FIXED_FIELD_LENGTH));
    const unsigned int size_2 = std::stoi(s.substr(FIXED_FIELD_LENGTH, FIXED_FIELD_LENGTH));
    o1 = s.substr(2 * FIXED_FIELD_LENGTH, size_1);
    o2 = s.substr(2 * FIXED_FIELD_LENGTH + size_1, size_2);
    o3 = s.substr(2 * FIXED_FIELD_LENGTH + size_1 + size_2);
}
} // namespace MultipartSplitMerge

At this point I wouldn't change the code anymore, unless I see via profiling that split or merge is a bottle-neck.

If you really notice that merge is a bottle-neck, you can use sprintf, but I guess that the compiler should optimize above code.


You are building a dynamic insert statement with parametrized values.  This works and there's nothing wrong with this method.  It may even be the best method for your circumstance.  It works well when your table is "small".  I have a rather large database which grows monotonically.  We keep adding rows and never remove any.  When your table grows beyond a certain point that is specific to your table design, inserts get very slow.  At this point, you will want to consider using the SqlBulkCopy class.  You insert the values into a DataTable and then do a bulk insert.  This is much faster because it uses a SQL Server specific method of loading data faster.  The SqlBulkCopy link has sample code.


It is generally advisable to parallelize loops at the absolute outermost level possible. Creating new OS threads, dividing up the relevant loop, and allocating data in the private address space for each thread all take up time, as does synchronization once the parallel task is over. Often, this overhead can outweigh any benefit that parallelism might have conferred in the first place. Whenever you use OpenMP to parallelize a task or loop, it has to be large enough to amortize the cost of spawning threads.

I would hoist as many parallel directives to the outermost loop as possible, and avoid having nested parallel directives. You may have to switch from using omp parallel for to just using omp parallel at the outermost level, then having some logic to explicitly decide which part of the data each thread works on depending on its thread number.

You'll have to be the judge of whether this is actually the problem or not; I only did a shallow read of your code, and the work that gets parallelized in the inner loops might actually be large enough that this is not the consideration at all.

Finally, there are alternatives to OpenMP for shared-memory parallel programming, e.g. Intel's Threading Building Blocks. OpenMP is pretty crude in the grand scheme of things, so you might find task-based parallelism easier or more fun to work with. You get to pretend like you have as many parallel threads of execution as you want, and the library manages farming out the tasks you define to the existing OS threads.


Find the locally biggest or equal values including corners in an array

First off you can change the while loop to a for loop.

for i in range(1, len(vals)):

This makes the program easier to understand. As then there is no i += 1.

It is also un-pythonic to do:

if len(vals) == 0:

Instead do:

if not vals:

As you want it to work with edge cases, what about generators? And other objects that are iterable, but not index-able.

I would change the if not vals: to a try except.

vals = iter(vals)
try:
    prev = next(vals)
except StopIteration:
    return []

And then you can change the for loop to use enumerate.

for i, curr in enumerate(vals, 1):
    if curr > prev:
        is_candidate = True
        buff = [i]
    elif curr == prev and is_candidate:
        buff.append(i)
    else:
        if is_candidate:
            res += buff
        is_candidate = False
        buff = []
    prev = curr

now it will work with anything that is iterable. And so it will work with generators.

Both yield and list.append are \$O(1)\$. However I like to think that list.append is \$O(n)\$. This is as lists rely on the amortized worst case to be \$O(1)\$.

From the Python time complexity page.

  Internally, a list is represented as an array; the largest costs come from growing beyond the current allocation size (because everything must move)

So using range, assuming you're using Python3, and generators can be better.

def look_for_maximas(vals):
    def res(vals):
        vals = iter(vals)
        # Exploiting for-loops and generators. It's kinda surprising this works.
        prev = next(vals)

        start = 0
        # Has to be in scope for the last yield.
        i = 1
        for curr in vals:
            if curr > prev:
                start = i
            elif curr < prev:
                if start is not None:
                    yield range(start, i)
                start = None
            prev = curr
            i += 1

        if start is not None:
            yield range(start, i)

    for range_ in res(vals):
        for i in range_:
            yield i

It is not as fast as a NumPy or SciPi solution, but can be a lot faster than using lists.

I tested this by doing assert list(look_for_maximas(...)) == .... And it worked for them all. However I don't have repeat, and removed that test.


"specific case" object that stands for "any object" : is it a good idea ?

I'd try to keep it as simple as possible. Instead of multiple in-line conditionals or a weird abstraction, I think a single full-fledged indented conditional makes things very clear. There are two scenarios, write two branches:

class ThingsController < ApplicationController
  def index
    if params[:category_id].present?
      @category = Category.find(params[:category_id])
      @things = @category.things
    else
      @category = nil
      @things = Thing.scoped
    end
  end
end


Function that shows markers all at once or with a delay

Make a helper function
One way to simplify this is to use a function to abstract removing the class name from the element. For example, create one like removeInactiveClassToElement:
removeInactiveClassToElement = (el) =>    el.classList.remove('inactive');

Then just call that function when necessary. For the case when calling in setTimeout(), use Function.bind() to make a partially-applied function, passing null as the thisArg argument, and then element as the first argument.
if (delay) {
    setTimeout(removeInactiveClassToElement.bind(null, element), delay * i);
}
else {
    removeInactiveClassToElement(element)
}

As you can see above, I switched the logic around so that the delay is added when delay has a value, and used that instead of this.delay, though if you wanted to set that property on the instance you could do that...
Functional approach
One could also use Array.forEach() instead of using the for statement. While it could slow performance (due to an extra function call on each iteration), it could cut the first couple lines out (e.g. assigning const element = this.elements[i];).
this.elements.forEach((marker, i) => {
    if (delay) {
        setTimeout(removeInactiveClassToElement.bind(null, marker), delay * i);
    }
    else {
        removeInactiveClassToElement(marker)
    }
});

Expand the snippet below for a demonstration, where clicking the image will add marker dots.

//helper functions
addInactiveClassToElement = (el) => el.classList.add('inactive');
removeInactiveClassToElement = (el) =>    el.classList.remove('inactive');
class MarkerList {
  constructor() {
    this.elements = [];
  }
  add(x, y) {
    const marker = document.createElement('div');
    marker.classList.add('marker');
    marker.setAttribute('style', 'left: ' + x + 'px; top: ' + y + 'px;');
    document.body.append(marker);
    this.elements.push(marker);
  }
  hideAll() {
    this.elements.forEach(addInactiveClassToElement);
  }
  showAll(delay) {
    this.elements.forEach((marker, i) => {
      if (delay) {
        setTimeout(removeInactiveClassToElement.bind(null, marker), delay * i);
      }
      else {
        removeInactiveClassToElement(marker)
      }
    });
  }
}
document.addEventListener('DOMContentLoaded', function() {
  var markers = new MarkerList();
  this.addEventListener('click', function(clickEvent) {
    if (clickEvent.target.id == 'hide') {
      markers.hideAll();
    } else if (clickEvent.target.id == 'show') {
      markers.showAll(delay.value);
    } else if (clickEvent.target.id == 'image') {
      markers.add(clickEvent.clientX, clickEvent.clientY);
    }
  });
});
.marker {
  background-color: #f00;
  width: 2px;
  height: 2px;
  position: absolute;
}
.inactive {
  display: none;
}

<button id="hide">
  Hide all
</button>
<button id="show">
  Show all
</button>

 Delay:
 <input id="delay" type="number" value="2000" />


Rock Paper Scissors Lizard Spock in JQuery

Write down the rules in an object. If an object contains a key, it means it can beat it.

Also, you're writing a javascript game, not jQuery. jQuery is a javascript library.

var rules = {
  rock: {
    scissors: true,
    lizard: true
  },
  scissors: {
    paper: true,
    lizard: true
  },
  lizard: {
    paper: true,
    spock: true
  },
  spock: {
    rock: true,
    scissors: true
  },
  paper: {
    rock: true,
    spock: true
  }
};

function play(opt1, opt2) {
  if (opt1 === opt2) {
    return "Draw";
  }

  if (rules[opt1][opt2]) {
    return "You win";
  }

  return "You loose";
}

console.log(play("rock", "scissors"));
console.log(play("paper", "paper"));
console.log(play("lizard", "spock"));


Your use of an array to store previous entries is convenient, but it requires a lot of memory use for values that will be thrown away and not reused. It's very simple to keep the two most recent values in simple variables, and not have the array at all.

Consider:

sum = 0
current = 1
previous = 1

while True:
    fib = current + previous
    if (fib > 4000000):
        break

    previous = current
    current = fib

    if (fib % 2 == 0):
        sum += fib

print sum

By eliminating the array you save a lot of management time, and space.

The code above contains a break condition inside the infinite loop instead of a loop condition. This is a common practice solution in Python for a do-while loop instead of a while-do loop.


Extract three letter pattern from a given list

Naming

I have two problems with your naming:

First, you don't use underscores to separate words. Instead of uniquepattern, use unique_pattern.

Second, your names don't actually tell me anything! Functions, particularly non-method functions, should include a verb unless the verb is implicitly get or is. And implicit is needs to be used with some caution.

So rather than unique_pattern, the name should be some phrase reflective of what your function does. Since you mention "scaffold names", perhaps that function should be group_scaffold_names_by_unique_pattern?

Or maybe the unique pattern has another name? Like prefix? (See my question in the comments.) So perhaps it should be group_scaffold_names_by_prefix?

Is that long? Yes. Does it says what happens? Also, yes. Clarity for the win!

Redundancy. Repetition. Duplication. Multiple Copies.

In coding, if you find yourself typing something for the second time, STOP! Whatever this is needs to be stored once and referenced from different places. Write a function. Store text in a variable. Create a class. Do whatever it takes, but DON'T REPEAT YOURSELF. (This is called the "DRY" principle.)

This code is repeated:

    pattern_name = re.search(r"[A-Z]{1}[a-z]{2}", name)

What does it do? Well, it appears to be used to extract the first matching pattern as the "key" for each name in the list.

So let's write a function for this:

def extract_key(name):
    """ Extract unique pattern from a scaffold name.
        Apparently, patterns are just the first three characters,
        so don't use regexes, just grab the substring.
    """
    return name[:3]

Use the standard library

You have a separate function that pulls out the keys (unique patterns) from the names, and returns a uniquified list of them, which you apparently use only to initialize the keys of a dictionary.

Instead of doing that, just use collections.defaultdict to create a dictionary that starts with empty lists:

import collections

groups = collections.defaultdict(list)

With that code, you can be sure that groups[key] is a list (unless you explicitly override it with some non-list value). So let's write your function again:

import collections
from typing import Dictionary, Iterable, List

def group_scaffold_names_by_prefix(names: Iterable[str]) -> Dictionary[str, List[str]]:
    """ Given a list of scaffold names, return a dictionary that
        groups them together by their prefix.
    """
    groups = collections.defaultdict(list)

    for name in names:
        groups[extract_key(name)].append(name)

    return groups


Your problem specification is unclear, and the code may be wrong as a result.  What exactly do you mean by "Unicode characters"?  What if a file contains just two bytes, 0x20 and 0x5D — is that two ASCII characters (a Space  and a Right Square Bracket ]), or is that one UTF-16 character (U+205D Tricolon ⁝)?

Unless you have a clear definition of what you mean by "Unicode", and have a special reason for detecting non-ASCII characters specifically, you may be better off opening the file with a latin_1 encoding and just checking is_printable().  In UTF-8, any multibyte sequence will have the leading bit set in all but the last byte, which would place it outside the string.printable range.  You would reject the same files as before, just with a less specific reason given.

For scalability, it would be better to read fixed-size blocks (perhaps around 8 kB) instead of the entire file at once.  It might also be more efficient to check c in set(string.printable) rather than c in string.printable.


Which of these two is better in terms of readability and function?

These aren't completely the same.  The first will return a List<T> and the second will return an IEnumerable<T>.

You would need to make this change in order for these to be equivalent.

var list = (from s in _surveyList
            where s.Date.Equals(selectedDate)
            select s.Joint).ToList();

But to answer your question it really comes down to personal preference.  What do you feel more comfortable with?  What has your team agreed on?

There are cases where you have to use Method Syntax over Query Syntax.  And there are some cases when one will be more readable then others.  You will have to make that determination yourself.

Check out this question over on Stack Overflow.

https://stackoverflow.com/questions/8037677/linq-query-syntax-vs-method-chains-lambda

That question was ultimately closed as being not constructive (opinion related) as I'm sure this one will be also.


I would replace your last lines with return counter == 0 as it is more compact and easier to read


You don't need to perform any join at all.

SELECT ParentId AS [Post Link]
     , OwnerUserId AS [User Link]
     , COUNT(Id) AS Answers
    FROM Posts
    WHERE
        ParentId IS NOT NULL           -- ← Answers only
        AND OwnerUserId <> 0
    GROUP BY ParentId, OwnerUserId
    HAVING Count(id) > 1
    ORDER BY Answers DESC;

Your instinct probably tells you that you need a JOIN to obtain the question titles. However, in Stack Exchange Data Explorer, there is a special feature: provide a PostId in a column named [Post Link], and it will take care of the presentation for you (implicitly doing a JOIN).


Is this an efficient way to implement Merge Sort in C++?

A single most important property of a merge sort is stability: equal elements maintain their relative order. This

    *pr++ = (*p1 < *p2) ? *p1++ : *p2++;

is a very typical mistake. In case *p1 == *p2, the element will be merged from the second array. Stability is lost. Not a problem for integers, of course, but keep in mind. The fix is simple:

    *pr++ = (*p2 < *p1) ? *p2++ : *p1++;


There's a little-known, though powerful feature of Java's LinkedHashMap code, and it is purpose-built for managing caches like yours. In your case, you should create the Map with the access-order constructor:

private static final class MyCache extends LinkedHashMap<String, String> {

    private final int limit;

    public MyCache(int limit) {
        super(limit, 0.75f, true);
        this.limit = limit;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
        return size() > limit;
    }
}

Note how you can override the removeEldestEntry method?

If you put this all together in an application, it looks like:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;

public class PropertiesFileMRUCache {
    private static final class MyCache extends LinkedHashMap<String, String> {

        private final int limit;

        public MyCache(int limit) {
            super(limit, 0.75f, true);
            this.limit = limit;
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
            return size() > limit;
        }
    }

    private final MyCache cache;

    private final Path propertiesFile;

    public PropertiesFileMRUCache(int limit, String file) {
        cache = new MyCache(limit);
        propertiesFile = Paths.get(file);
    }

    public String getCapital(String country) {
        return cache.computeIfAbsent(country, c -> readFromFile(c));
    }

    private String readFromFile(String country) {
        final String prefix = country + "=";
        try (Stream<String> lines = Files.lines(propertiesFile)){
            return lines.filter(line -> line.startsWith(prefix))
                    .map(line -> line.substring(prefix.length()))
                    .findFirst()
                    .orElse(null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        PropertiesFileMRUCache pfc = new PropertiesFileMRUCache(8, "ccap.properties");
        pfc.getCapital("India");
        pfc.getCapital("USA");
        pfc.getCapital("UK");
        pfc.getCapital("Kuwait");
        pfc.getCapital("Iraq");
        pfc.getCapital("Canada");
        pfc.getCapital("Australia");
        pfc.getCapital("India");
        pfc.getCapital("India");
        pfc.getCapital("India");
        pfc.getCapital("Germany");
        pfc.getCapital("India");
        pfc.getCapital("Germany");
        pfc.getCapital("China");
        pfc.getCapital("Pakistan");
        System.out.println(pfc.cache);
    }
}

Note how I have also hacked around in your readFromFile method. I have made it NIO2-based using Paths, and Files. This is the best practice way to do it in Java 8. I have also streamed the lines, which I believe will help. A try-with-resources cleanly closes the stream too. Additionally, a computeIfAbsent is the right way to reuse an existing entry, and create a missing one.

There are a number of things you should identify as being different. Consider the extension of the LinkedHashMap to be the most significant, and the improved use of the computeIfAbsent to be second most important.