public class Shuffler<T> : IEnumerable

Why not IEnumerable<T>??!

        private readonly List<T> _allItems = new List<T>(); // All items used in the shuffler

The types in this line raise two red flags in my mind.

Code to the interface, not the implementation. The type of the field per se should be an interface: maybe IList<T>, maybe ICollection<T>, or maybe even something else.
With respect to maybe even something else: should it be ISet<T>? The explanation given for the use case suggests strongly that elements should not be repeated, because if they are repeated it's going to be complicated to avoid playing the same track twice in a row.

        private readonly List<T> _pool = new List<T>(); // Remaining items for current series

Again, code to the interface. Here IList<T> is justified because the ability to select by index is important for performance.

        private T _last; //Last object extracted from the pool

If "last" here means "most recent" then the methods further down seem buggy.

        private int PoolCount
        {
            get { return _pool.Count; }
        }

Are you deliberately avoiding the arrow syntax?

        private int PoolCount => _pool.Count;

is going to become increasingly common.

        public Shuffler(ICollection<T> allItems)
        {
            if (allItems.Count == 0) throw new ArgumentException("ERROR: initialization list cannot be empty !");
            _allItems.AddRange(allItems);
            PopulatePool();
        }

I concur with VisualMelon's observations on this constructor: there's no reason to prohibit empty inputs, there's no need to populate the pool yet, and there's no reason to require ICollection<T> rather than IEnumerable<T>.

        public T GetNext()
        {
            if (IsPoolEmpty())
            {
                PopulatePool();
            }
            return PopRandomElement();
        }

vs

        public IEnumerator GetEnumerator()
        {
            while (PoolCount > 0)
            {
                yield return PopRandomElement();
            }
        }

Firstly, I find this API very confusing. It would make more sense to me if both methods ran forever, repopulating the pool if it runs dry.

Secondly, IsPoolEmpty() vs PoolCount > 0 is inconsistent. IMO factoring out IsPoolEmpty() is overengineering: I would inline it.

        private T PopRandomElement()
        {
            if (PoolCount == 0) throw new ArgumentException("ERROR: initialization list cannot be empty !");
            int randomIndex = _random.Next(PoolCount);
            T item = _pool[randomIndex];
            _pool.RemoveAt(randomIndex);
            if (IsPoolEmpty()) _last = item;
            return item;
        }

You asked

  Is it efficient enough ?

Enough depends on your requirements, but the answer to the question "Is it as efficient as it could be?" is "No". _pool.RemoveAt has to shuffle along every later element in the list. In the worst case the random number generator will return a long string of 0. The standard solution is a swap.

        private T PopRandomElement()
        {
            System.Diagnostics.Debug.Assert(PoolCount > 0);
            int randomIndex = _random.Next(PoolCount);
            _last = _pool[randomIndex];
            _pool[randomIndex] = _pool[PoolCount - 1];
            _pool.RemoveAt(PoolCount - 1);
            return _last;
        }

This now takes constant time rather than linear time in the size of the pool.

        private void PopulatePool()
        {
            _pool.Clear();
            _pool.AddRange(_allItems);
            if (PoolCount > 1) // If _allItems is size 1 we don't remove from the pool : it would be empty
            {
                RemoveLastFromPool();
            }
        }

        private void RemoveLastFromPool()
        {
            _pool.Remove(_last);
            _last = default(T);
        }

Again, a linear removal could be replaced by a swap and a constant time removal.

But I wonder whether this actually meets the spec. Rather than removing _last from the pool entirely, didn't you just want to guarantee that it won't be the first element picked after repopulating the pool?

In fact, I'd be inclined to take this further. Suppose we refactor so that PoolCount is backed by its own field rather than _pool.Count, and that we have an additional field (or field-backed property) DelayCount.

If we replace _pool.RemoveAt(PoolCount - 1); with PoolCount--; then when PoolCount gets to 0, the pool contains the entire play list in reverse order of when they were last played. Now

PoolCount = _pool.Count;
DelayCount = N;
for (int i = 0; i < DelayCount; i++)
{
    var tmp = _pool[i];
    _pool[i] = _pool[PoolCount - DelayCount + i];
    _pool[PoolCount - DelayCount + i] = tmp;
}

swaps the first N elements up to the end. Adjust the PopRandomElement method a bit more:

        private T PopRandomElement()
        {
            System.Diagnostics.Debug.Assert(PoolCount > 0);
            System.Diagnostics.Debug.Assert(PoolCount > DelayCount);

            int randomIndex = _random.Next(PoolCount - DelayCount);
            var tmp = _pool[randomIndex];
            _pool[randomIndex] = _pool[PoolCount - 1];
            _pool[PoolCount - 1] = tmp;

            PoolCount--;
            if (DelayCount > 0) DelayCount--;

            return tmp;
        }

The effect is to guarantee that no track will repeat within N of the previous time it occurred. You can then make N settable with a public property or derive it from _pool.Count according to some hard-coded policy (e.g. a fixed percentage).

        public List<T> GetAllPossibleValues()
        {
            return new List<T>(_allItems);
        }

Why List<T>? In fact, is this method even useful?

        public void Add(T element)
        {
            _allItems.Add(element);
            PopulatePool();
        }

I don't see why it's desirable to populate the pool here. In addition to VisualMelon's observations, by populating the pool before reaching the end you lose the guarantee not to play the same track twice.


A controller? No. A model? Sure. Not sure if Symfony defines a controller differently, but this is not what I think of as a controller.

As for refactoring, the easiest way would be to break it up into smaller methods. For instance, right off the bat I see at least 6 different potential methods here. You could create a bunch of smaller methods that returns a part of the bag (messaging, charting, etc...) and then merge them all together. In fact, that's the only real improvement I can see. I feel bad leaving such a short answer, so here's an example of a couple of those smaller methods, which is actually about half that code.

private function getUsageCharts ( $usage ) {
    $rawData = $usage->getRawData();
    $start   = $usage->getStartDate();
    $end     = $usage->getEndDate();

    $line_chart = $charting->createMessagesLineChart($rawData, $start, $end);
    $pie_chart  = $charting->createMessagesPieChart($rawData);

    return compact( 'usage', 'line_chart', 'pie_chart' );
}

private function getMessagingFields( $loggedUser ) {
    $messaging = $this->get('messaging.helper');

    $subscription = $messaging->createSubscriptionFromUser($loggedUser);
    $usage = $messaging->createUsageFromSubscription($subscription);
    $inhibitor = $messaging->createInhibitor($usage, $subscription);

    extract( $this->getUsageCharts( $usage ) );//$line_chart, $pie_chart
    return compact( 'subscription', 'usage', 'inhibitor', 'line_chard', 'pie_chart' );
}

Hope this helps!


You can make these #defines:

#define SHA1_DIGESTLENGTH 20
#define SHA1_BLOCK_LENGTH 64
#define COUNTER_LENGTH 8

into a more concise enum:

typedef enum { COUNTER=8, SHA1_DIGEST=20, SHA1_BLOCK=64 } Length;

This could also be done with SECRET and COUNTER, but each hex value would need a name.

If you use the enum recommendation, you may need to rename the second COUNTER to avoid possible name-clashing.  Perhaps rename it based on what the counter is for.
You don't need your own typedefs for these:

typedef unsigned           char uint8_t;
typedef unsigned short     int uint16_t;
typedef unsigned           int uint32_t;

Prefer to use the typedefs already defined in <stdint.h>.
For unformatted output with a newline, use puts() instead of printf():

puts("Some text...");

I'd recommend splitting this program into separate functions.  This will make it easier to tell how the it works and make it easier to maintain.  A function should have one purpose, andmain() should have minimal implementation (such as acquiring input and calling other functions).
There's no need to call exit(1) within main().  Just return 1.

The return 0 is also not needed at the end.  Reaching this point implies successful termination, so the compiler will do this return for you.


My first comment would be to comment your code.

You need documentation so I know what your function is meant to do. "Sum any given finite Arithmetic Progression" would suffice if you passed in an ArithmeticProgression, but instead you pass in some bounds. Writing an arithmetic progression type would be simple and might even help a little, but you still need to document that.

I don't know what algorithm you're trying to use. You've evidently taken some maths for sums of arithmetic progressions and applied it to the problem, but there's no way for me to verify that the maths is correct or that the code implements it correctly without at least rudimentary explanation of what you did. I could reimplement it myself, but code should be verifiable much more easily than that.


You open with

  SELECT DISTINCT

. Is this really necessary? This is a performance killer. Perhaps duplicates can only occur between certain tables. If that were the case, put the distinct as deep as you can in query, even if this means adding additional nested queries.


K&R 1-20 Converting tabs to spaces using idiomatic C

I don't think this program is correct, according to my interpretation of tab stops.  One problem is that the column count should reset to 0 after every carriage return or newline character encountered.

Your program is vulnerable to buffer overflow.  This may be acceptable for a beginner, as long as you acknowledge the problem, but this code should never be put into production use.  (You may think that your buffers are generously sized, but a malicious attacker will scoff at whatever limit you choose.  There is no substitute for proper bounds checking.)  One simple strategy you could use is to minimize the use of a buffer by printing output on every call to detab() — your buffer would not need to be much larger than TABSTOP bytes.

In your detab() function, you want to treat i as an in/out parameter (i.e., the function alters the parameter and passes it back to the caller).  It is customary to accomplish this in C by passing a pointer to i, like this:

void func(int *in_out_param) {
    while (0 != *in_out_param % 4) {
        (*in_out_param)++;
    }
}

void caller() {
    int i = 2;
    func(&i);
    printf("%d\n", *i);  /* prints 4 */
}

Your variables are cryptically named.  While short variable names are acceptable and even encouraged as, say, dummy variables for iteration where their purpose is obvious, they should not be used as a matter of habit.  In particular, it is important to give descriptive names to function parameters, since they help prevent accidental misinterpretation by the function's users.  I would suggest this function interface:

/**
 * Converts input character c at column col into a string, with the output
 * placed in buf.  If c is a tab character, it is expanded into the appropriate
 * number of spaces.  The buffer size should be at least one more than tabwidth.
 */
void detab(unsigned int tabwidth, char c, unsigned int *col, char *buf, size_t bufsize)

For best performance, avoid reading one character at a time using getchar().  For this application, I recommend fgets(), which reads one line at a time (or up to the buffer size or until end-of-file, whichever is shortest).  Admittedly, that does complicate the solution quite a bit.


Processing the number as a string

Don't. In general, converting a numerical value to a string and using some string processing on what was once a number is a code smell. You of course often need to convert numbers to strings for output and formatting, but mathematical operations should be done mathematically.

If you for instance wanted to check whether the second-last digit is even, you can divide your number by 10 and check the oddity of that result. That's an arithmetic check without involving any string processing.

The correct algorithm

Whenever you approach a problem, you should think about the correct algorithm to solve it, and do some research, if applicable. Leap years for instance can be detected by a much simpler algorithm. Leap years in the Gregorian calendars are years that are divisible by 4 but not 100, unless they are also divisible by 400. So:

If it's not divisible by 4, it's not a leap year.

If it's divisible by 4, it's a leap year if: it's not divisible by 100, or it's divisible by 400.

Now that looks almost like an algorithm in code. Which you can write along the lines of

if (year % 4 == 0) {
    if (year % 100 != 0) {
        return true; //Divisible by 4 and not by 100, leap year
    }
  return (year % 400 == 0); //Divisible by 4 and by 100. Leap year if divisible by 400.
}
return false; //Not divisible by 4 - not a leap year.

Of course that could also be a one-liner, but this perhaps makes the decision logic a bit more clear.

Java 8

In Java 8, a lot of functionality for handling calendars has been added, such as the Year class. The following would work:

return Year.isLeap(year);

General

It's hard not to notice that your formatting is inconsistent. Sometimes space before opening braces, sometimes not. Sometimes you surround a single statement with braces, sometimes not. Those are largely up to individual preference (although I think space before braces is a must, as is enclosing single statements in braces), but consistency is definitely very important.

Also, as the answer by RubberDuck notes, it's not needed or a good practice to write code of the if (something) return true; else return false type when you can just return the condition directly.


Handling exceptions within the action is a cross-cutting concern that can be extracted and placed into one of the available extensiblity points. This will greatly reduce the repeated  exception handling in all controller actions.

Reference Global Error Handling in ASP.NET Web API 2

  Exception handlers are the solution for customizing all possible responses to unhandled exceptions caught by Web API.

With that the above controller in your example can be refactored to something as simple as

public class SecurityController : ApiController {
    private readonly ISecurityProxy client; // abstraction of proxy class

    public SecurityController(ISecurityProxy client) {
        this.client = client;
    }

    [HttpPost]
    public IHttpActionResult StartSession([FromBody] StartSessionRequestModel requestModel) {
        if (ModelState.IsValid) {
            var requestMessage = new StartSessionRequest {
                Username = requestModel.Username,
                Password = requestModel.Password
            };
            StartSessionResponse result = client.StartSession(requestMessage);
            return Ok(result);
        }
        return BadRequest(ModelState);
    }
}

Why so lean?

The SecurityFacade has been abstracted out as classes should depend on abstractions and not be tightly coupled to concretions as the original example implies that dependency injection is already being used.

The ILogger and exception handling is no longer needed in the controller as that is a cross-cutting concern that can be moved to an ExceptionHandler

public class WebApiExceptionHandler : ExceptionHandler {
    private readonly ILogger logger;

    public WebApiExceptionHandler(ILogger logger)
        : base() {
        this.logger = logger;
    }

    public override void Handle(ExceptionHandlerContext context) {
        var innerException = context.ExceptionContext.Exception;

        // Ignore HTTP errors.
        if (innerException.GetType().IsAssignableFrom(typeof(System.Web.HttpException))) {
            return;
        }

        //Handle SOAP errors as bad requests
        IHttpActionResult result = null;
        if (innerException.GetType().IsAssignableFrom(typeof(SoapException))) {
            var soapException = innerException as SoapException;
            result = new BadRequestResult(soapException.Code.Name, context.Request);
            context.Result = result;
            return;
        }

        //Handle and log general errors
        logger.Error(innerException);
        result = new InternalServerErrorResult(context.Request);
        context.Result = result;
    }

    private class BadRequestResult : IHttpActionResult {
        public BadRequestResult(string message, HttpRequestMessage request) {
            Message = message;
            Request = request;
        }

        public HttpRequestMessage Request { get; private set; }
        public string Message { get; private set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
            var model = new {
                Message = Message
            };
            var response = Request.CreateResponse(HttpStatusCode.BadRequest, model);
            return Task.FromResult(response);
        }
    }
}

  An exception handler indicates that it has handled an exception by setting the Result property to an action result (for example, an ExceptionResult, InternalServerErrorResult, StatusCodeResult, or a custom result). If the Result property is null, the exception is unhandled and the original exception will be re-thrown.

the handler can now be added as a global error handler for API calls.

The following extension method is added to simplify adding the handler when configuring the Web API at start up.

public static class WebApiConfig {

    public static void Register(HttpConfiguration config) {

        //... code removed for brevity

        config.ReplaceExceptionHandler();
    }

    /// <summary>
    /// Global Exception handling
    /// </summary>
    /// <remarks>
    /// There must be exactly one exception handler.
    /// (There is a default one that may be replaced.)
    /// </remarks>
    public static HttpConfiguration ReplaceExceptionHandler(this HttpConfiguration config) {
        var errorHandler = config.Services.GetExceptionHandler();
        if (!(errorHandler is WebApiExceptionHandler)) {
            var service = config.Services.GetService(typeof(WebApiExceptionHandler));
            config.Services.Replace(typeof(IExceptionHandler), service);
        }
        return config;
    }
}


Welcome to the code review community. The code looks clean, and follows the PEP8 style guide. Here are a few suggestions/modifications you can make though:

Do not use global variables.

Instead of calling agenda() at the end, put it inside the if __name__ block.

Since you're working with python 3.8+, you may also add type hinting for function arguments.

For user input/validation, you can make use of a while loop:
 from typing import List

 def read_user_input_from_options(message: str, valid_inputs: List = None):
     """
     Show `message` in the console while asking for user input.

     If `valid_inputs` is not provided, returns the value from user as is.
     """
     if valid_inputs:
         valid_inputs = map(lambda x: x.upper(), valid_inputs)
     while True:
         user_input = input(message)
         if not valid_inputs:
             return user_input
         user_input = user_input.upper()
         if user_input in valid_inputs:
             return user_input
         print("Invalid option chosen. Try again.")

The above is an example suited for your case, where all the input option you need are capitalised alphabets. It can be extended to support other validators as per requirements.

Use multiline strings. Makes it more readable. It is more a personal preference than rules to live by.

You can map the option to a function call (see below):
 def quit_program():
     print("Have a nice day!")
     return

 def main():
     OPTION_TO_FUNCTION = {
         "A": look_at_agenda,
         "B": create_task,
         "C": clear_list,
         "D": quit_program,
     }
     option = read_user_input_from_options(
         """
         What would you like to do?
         A - look at agenda
         B - create task
         C - clear list
         D - quit
         """,
         valid_inputs=["a", "b", "C", "d"],
     )
     return OPTION_TO_FUNCTION[option]()

where main is the function called from inside your if __name__ == "__main__" block.

Make use of a class to keep the state of current execution. This would accompany my point about avoiding globals as well.


-- adding this as an answer because I can't comment.

The answer referenced in ggorlen's comment, can be improved by remarking that a (negative number % 10) is a negative number, so there is no need for sign checking.

const reverse = val => {
    let res = 0;
    const Base = 10;
    while (val) {
        res = res * Base + (val % Base);
        val = (val / Base) | 0;
    }
    return (res | 0) == res ? res : 0;
}

Tests:

reverse(1) === 1;
reverse(-1) === -1
reverse(0) === 0
reverse(Math.pow(2,31) - 1) === 0
reverse(Math.pow(-2,31)) === 0
reverse(1463847412) === 2147483641
reverse(1463847413) === 0

By the way, what's the reasoning behind "x = (x - x - x)"? x-x evaluates to zero. so that's just x = - x.


Hi there! I've recently been getting into java and was wondering how I can clean up or condense the code for this problem I've been working on

Style

Please use proper indentation. It is generally considered good practice to indent the code inside a method. This will make your code more legible.
The use of curly brackets is inconsistent (have a look at the calculate-method. In Java, the most common use of curly brackets looks like this:

public static void calculate(...) {
    //Commands here
}

For variable names the lowerCamelCase is used. So num_items becomes numItems and item_cost becomes itemCost.

Input

You have been thinking about how to stop the user from making invalid inputs. You are using:

while (numItems < 1 || 10 < numItems) {
            errors += 1;
            System.out.println("Please enter the number of items bought (1-10): ");
            numItems = scan.nextInt();
        }

This will stop the user entering other numbers than intended. The problem is that your program crashes, when the user enters not even a number (for example "hi"). This can be solved with the following code (use import java.util.InputMismatchException;):

while(true) {
        try {
            numItems = scn.nextInt();
            if(numItems < 1 || 10 < numItems) {
                throw new InputMismatchException()
            }
            break;
        }
        catch(InputMismatchException e) {
            System.out.println("Invalid Input!");
            scn.nextLine();
        }
}

Also, you have initialized more than one scanner in your program. That's not necessary. Just initialize one in the beginning and use it for the whole time.

Other

I removed the variable errors, because it is not useful to tell the user how many errors he/she made. But that's just a personal opinion.
It's not necessary to restrict the number of items and their prices, but I have left it in the code so you can see how to restrict it.

All in all your code could look like this:

import java.util.Scanner;
import java.util.InputMismatchException;

public class Taxes {

    public static void main(String[] args) {

        double subtotal = 0;
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the number of items bought (1-10): ");
        int numItems;
        while(true) {
            try {
                numItems = scan.nextInt();
                if(numItems < 1 || 10 < numItems) {
                    throw new InputMismatchException();
                }
                break;
            }
            catch(InputMismatchException e) {
                System.out.println("Invalid Input!");
                scan.nextLine();
            }
        }

        for (int i = 1; i <= numItems; i++) {
            System.out.println("Please enter the price of item " + i);
            Double itemCost;
            while(true) {
                try {
                    itemCost = scan.nextDouble();
                    if(itemCost < 1 || 1000 < itemCost) {
                        throw new InputMismatchException();
                    }
                    break;
                }
                catch(InputMismatchException e) {
                    System.out.println("Invalid Input!");
                    scan.nextLine();
                }
            }
            subtotal += itemCost;
        }
        System.out.println("Please enter the tax rate of GST in %: ");
        double gRate;
        while(true) {
            try {
                gRate = scan.nextDouble();
                if(gRate < 0 || 14 < gRate) {
                    throw new InputMismatchException();
                }
                break;
            }
            catch(InputMismatchException e) {
                System.out.println("Invalid Input!");
                scan.nextLine();
            }
        }
        System.out.println("Please enter the tax rate of QST in %: ");
        double qRate;

        while(true) {
            try {
                qRate = scan.nextDouble();
                if(qRate < 0 || 17 < qRate) {
                    throw new InputMismatchException();
                }
                break;
            }
            catch(InputMismatchException e) {
                System.out.println("Invalid Input!");
                scan.nextLine();
            }
        }

        calculate(subtotal, gRate, qRate);
    }

    public static void calculate(double subtotal, double gRate, double qRate) {
        double gst = subtotal * (gRate/100);
        double qst = (subtotal + gst) * (qRate/100);
        double total = subtotal + gst + qst;
        System.out.println("GST: " + gst);
        System.out.println("QST: " + qst);
        System.out.println("Subtotal: "  + total);
    }
}

I will leave it to you to comment the code properly.


The problem with your approach is that your are trying to simultaneously satisfy two contradictory requirements: produce a robust cross-platform implementation, and explicitly deal with different hosts.

A better approach is to avoid any knowledge of the host's endianness by using shifts and or's. It is, however, perfectly fine to rely on network byte order being big-endian as that is an invariant.

Consider the conversion to network order first. This is the simpler direction as it is always fixed but, in C at least, you will need to write routines to deal with the different sizes of int. For now, we will deal with unsigned int only.

void uint_to_network(unsigned int value, unsigned char * buffer, size_t buffer_size)
{
    size_t nw_length = sizeof(value);

    if (buffer_size < nw_length) return; // Avoid potential overflow

    // Note that this loops until all possible locations in the
    // output stream are filled, automatically handling leading zeroes.
    while(nw_length != 0)
    {
        // Pre-decrementing nw_length deals with the zero-based nature
        // of C arrays and avoids us having to worry about the representation
        // of -1 as an unsigned value.
        nw_length--;
        buffer[nw_length] = value & 0xff;
        value >>= 8;
    }
}

Note that this code is written in terms of the network order, with no knowledge of the host's endianness. Thus, it is inherently cross-platform.

Converting from network to host follows a similar pattern.

unsigned int network_to_uint(unsigned char * buffer, size_t input_length)
{
    unsigned int result = 0;
    size_t decode_length;

    decode_length = (input_length > sizeof(unsigned int))
                      ? sizeof(unsigned int)
                      : input_length;

    for (size_t i = 0; i < decode_length; i++)
    {
        result <<= 8;
        result |= (unsigned int) buffer[i];
    }

    return result;
}

Again, the code is written in terms of the known network order and makes no reliance on the host order.

Also note that, whenever dealing with network side data, I always use the unsigned char format. This is because network data is basically a 'bit stream', and you should never try to deal with it as a different native data type. That way lies madness .. or at least very subtle bugs.

Now, in a production implementation where execution speed is all important, you would actually have two implementations of the routines. On a big-endian host they would be no-ops, or at worst a macro performing a cast. On a little-endian host, they would be heavily optimized based on the knowledge that conversion was always required. Then your build-script would link in the set of routines that made sense for the target: and you would have some intelligence in the build script if only to select the correct target-processor for the cross compiler.

But for a true cross-platform single-implementation solution, avoiding knowledge of the host's endianness is the only sure route to avoiding problems.

By the way, if you change the return type of network_to_uint to unsigned long long (or unsigned long if your compiler is too old for long long) it can deal with all of the unsigned integer types in the network data by passing in the correct value for input_length. But you will still need a different routine to deal with signed data. And remember that, for an unsigned int in the network data you need to specify the correct input length. A network int may not be the same size as your host's.

For signed data, you have to be a little more careful. There are hosts out there which store data with a separate sign bit (i.e. they can represent both positive and negative zero) and C is designed to run on those as well.

And really, my uint_to_network has the fault that it assumes sizeof(unsigned int) on the host is the same as its representation in a network data stream. It really ought to take an output_length argument instead of setting nw_length to sizeof(unsigned int). Then it can also be made to work for all unsigned data, because it only extracts the least significant bytes of the data.


Load stylesheet for "rem" value fallback to "px"

I have tested the following code in IE8 and Safari and it works, although I cannot test on the Galaxy Note or Opera Mini. The following javascript allows you to test rem support. Since IE9 or lower throws an error when you try to set as rem, I used a try{}catch(){} - newer browsers should remove the value as soon as its set when they don't support setting the value as such. I don't know if this solves all your problems (if the Galaxy allows you to set rem but doesn't apply it, then this won't work). I have used pure javascript, so you don't need support for anything else (like jQuery).
function supports(attribute, test){

    var supports = false;

    try {
        var div     = document.createElement("div");

        div.style[attribute] = test;

        if(div.style[attribute] === test){
            supports = true;
        }
    } catch(e){}

    return supports;
}

You could then test for rem support as such:
if(supports("fontSize", "1rem")){
    /* Rem supported, don't add your stylesheet */
} else {
    /* No rem support, add another stylesheet to make up for it */
}

This is a purer and simpler, and more reusable, version of your code. Sniffing user agents is generally a bad idea as they inevitably lead to confusion, and a user agent string in the future might match what you are testing for and therefore have an unexpected outcome. It is also best practise to allow for more universal solutions. You could, for example, use this same function to see if you can set background-imageto 1rem and it would return false.
Update
I have just done some testing with browser stack (which, granted, is an emulator) and the Galaxy Note 2 does support rem. And not because my function says it, I made a page with this code:
<!DOCTYPE html>

5EM

2(*5)EM/2REM

and the nested 2(*5)EM/2REMis smaller than the 5EM, which indicates its getting the base value from the html tag and not from the parent, indicating rem support.


It sounds like you're trying to group transactions by member_id and company_id, though in the code you posted you are only grouping by member_id and then overwriting the company with each new transactions' company.

If you pass a block to group_by, though, you can group by more than a simple method on the object, for instance you can group by an array of attributes that match, such as:

transactions.group_by { |transaction| [transaction.member_id, transaction.company_id] }

and then you still have to loop through and format the transactions how you want, but you can clean that up as well, by using map and each_with_object:

transactions.
  group_by { |transaction| [transaction.member_id, transaction.company_id] }.
  each_with_object({}) do |((member_id, _), transactions), data|
    data[member_id] = {
      # no need to keep rebuilding the company hash, all transactions belong to
      # the same company
      company: { id: transactions.first.company_id,
                 name: transactions.first.company_name },
      transactions: transactions.map do |transaction|
        {
          particulars: transaction.particulars,
          contribution: { contribution1: transaction.contribution1,
                          contribution2: transaction.contribution2 }
        }
      end
    }
  end

This can be cleaned up even more, by moving the generation of these hashes to presenters but that's just moving the code around at this point, regardless you still need to go through all the transactions and present them as the hash, so the loop is unavoidable.


If you do the checks in ascending order, you don't need greater then checks.
Since the only difference is the value of discount, you could use a dictionary.

static void Main(string[] args)
{
    Console.WriteLine("Please enter the quanitity of the product bought.");
    var x = Console.ReadLine();
    int x1 = int.Parse(x);

    Console.WriteLine("Please enter the price of the product bought.");
    var y = Console.ReadLine();
    double y1 = double.Parse(y);

    Dictionary<int, double> discountLevels = new Dictionary<int, double>
    {
        {100, 0.1},
        {200, 0.12},
        {500, 0.15}
    };

    double discount = 0.2;
    foreach (var discountLevel in discountLevels.OrderBy(discountLevel => discountLevel.Key))
    {
        if (x1 <= discountLevel.Key)
        {
            discount = discountLevel.Value;
            break;
        }
    }

    double outValue = 0;
    outValue = returnTotal(discount, y1, x1);
    Console.WriteLine("The total with the discount is R{0}", outValue);
}

The OrderBy ensures that the checks are done in the correct order.


Node.js parallel file download, the ES6 way

Things that come to my mind after a quick read:

do not use const someFunction = (...) => {...} instead of function someFunction(...) {...})
use module.exports even if it is a script
group functionality into functions; you have comments beautifully spaced, but a function name will be more readable and maintainable
try to have functions that do one thing; when explaining to someone what a function does, and you have to use and then you should split the function
try to use map, filter, etc. instead of having iterations with a variable (e.g. fileNumber)
whenever you have someString + someOther you could use string templating (i.e. ${someString}${someOther}
prefer using promises instead of callbacks; the code ends up being more readable; e.g. use bluebird.promisify
use a good eslint config (e.g. airbnb)

To enhance collaboration, you could use a github repository and reference it here.


Dictionary synonym lookup via networking

What about something like this?

val socket = new Socket(InetAddress.getByName("localhost"), 4444)
val out = new PrintStream(socket.getOutputStream)
val bs = BufferedSource(new InputStreamReader(socket.getInputStream, "utf8"))
out.println("LOOKUP "  + word)
out.flush()
val output = bs.getLines.find(_.contains("200"))
socket.close()
output

FWIW in the general case you could replace that sort of match construct you're using with something like this:

Option(curr).filter(_.contains("200"))


Code analysis

Let's run through your code bit by bit.

First a note about paths: use verbatim strings to disable escape sequences, so you don't need to escape those slashes: @"C:\myfile.m4a" instead of "C:\\myfile.m4a".

public static bool WriteAaray(string originalFile, List<float> myFloatPoints)
{

originalFile is a path, not a file (stream), and I'm not sure why it's called 'original', so I would rename it to filePath.
I'd also fix the typo in Aaray.

    FileStream inputFileStream = null;
    inputFileStream = new FileStream(originalFile, FileMode.Open);

The 'input' in inputFileStream is misleading: you're not reading from this file, you're writing to it. I'd rename it to just file.
There's no need for that first line: just write var file = new ... instead.
File streams are disposable, so it's better to use a using statement here.
Note that the File class contains several useful methods, such as File.Open, or the very convenient File.AppendAllText.

    var length = inputFileStream.Length;
    inputFileStream.Seek(length, SeekOrigin.Begin);

There's no need for that local variable (length): just pass file.Length directly into Seek.
Instead of manually seeking, consider opening the file with FileMode.Append. Not only does that seek to the end for you, it also creates the file if it doesn't exist yet (in your code that'll throw an exception, which will crash your program because you're not catching it).

    StringBuilder mystring = new StringBuilder();
    string myImpPoints = "[MYIMPPOINTS]";
    mystring.Append(myImpPoints);

While string builders are often more efficient than string concatenation, in this case you're only concatenating two strings (this header and the result of that string.Join call), so a string builder won't help here - it might even be less efficient. Note that string.Join uses a string builder internally, and with 5000 floats it certainly is useful there.
Again, no need for a local variable (myImpPoints) - just pass it into Append directly.

    var points = string.Join(",", myFloatPoints.Select(f => f.ToString()));
    mystring.Append(points);

There's no need for that Select call - one of the overloads of string.Join takes an IEnumerable<T>, so you can pass your list of floats in directly.
On the other hand, this only gives you 7 digits of precision. If that's a problem, then you should keep the Select part, but be sure to specify "R" (round-trip) or "G9" (recommended for performance reasons) as the to-string format.
Again, no need for a local variable (points).
Note that formatting and parsing string representations of floats is slower than writing and reading them as binary data.

    byte[] byteArray = Encoding.ASCII.GetBytes(mystring.ToString());
    inputFileStream.Write(byteArray, 0, byteArray.Length);
    inputFileStream?.Close();

Consider using a StreamWriter instead. That takes care of encoding and buffering, so you don't have to mess with string builder buffers and byte arrays and all that.
With a using statement around the file stream, you don't need to call Close manually here. Either way, you don't need an 'elvis operator' here - inputFileStream obviously won't be null.

    return true;
}

You're returning a boolean to indicate success, but that's actually somewhat misleading: this method can fail, but instead of returning false (which I would expect, with such a method signature) it'll throw an exception. Either catch it and return false (but then the caller won't know why it failed), or don't return anything and let the method throw (but document it).

Alternatives

5000 floats isn't a whole lot, so unless you need to create a lot of these files, the following code should be fast enough:

File.AppendAllText(filePath, "[MYIMPPOINTS]" + string.Join(",", values), Encoding.ASCII);

If, after actually measuring performance, that turns out to be too slow, then here's what your code could look like with the above notes taken into account:

using (var file = File.Open(originalFile, FileMode.Append, FileAccess.Write))
using (var writer = new StreamWriter(file, Encoding.ASCII)) // buffer size can be adjusted if necessary
{
    writer.Write("[MYIMPPOINTS]");

    if (values.Count > 0)
        writer.Write(values[0]);

    for (int i = 1; i < values.Count; i++)
    {
        writer.Write(',');
        writer.Write(values[i]);
    }
}


You may or may not consider this simpler:

(defn tail-cmd-2
  "Construct a tail cmd"
  [file n & ignore-patterns]
  (str "cat "
       file
       " | "
       (apply str (map #(format "grep -v \"%s\" | " %) ignore-patterns))
       "tail -f "
       (if n (str "-n " n))))

Or if you're willing to use the non-standard clojure.core.strint library, you can do the following.

(defn tail-cmd-5
  "Construct a tail cmd"
  [file n & ignore-patterns]
  (let [greps   (apply str (for [p ignore-patterns] (format "grep -v \"%s\" | " p)))
        minus-n (if n (str "-n " n))]
    (<< "cat ~{file} | ~{greps} tail -f ~{minus-n}")))

Here's the library source:
https://github.com/clojure/core.incubator


SqlCommand ExecuteReaderAsync helper method

DataContext

  [..]the creation of the DataContext seems a bit excessive

Why do you think so? Is creating the SqlCommand not excessive? You are instantiating it the same number of times.

If DataContext.Translate helps you to save time by not writing the mapping your self then I'd say it's fine. Just remember that DataContext is a disposable type too, so you should add one more using for it.

Naming

Apart from the DataContext you should try to make you code more consistent. This means, don't use abbreviations like conn or trans. Use full words especially for parameters.

Style

public static async Task<IEnumerable<T>> CommandExecuteReaderAsync<T>(
  SqlConnection conn,
  SqlTransaction trans,
  CommandType commandType,
  string commandText,
  IEnumerable<SqlParameter> parameters,
  CancellationToken token,
  int commandTimout)

I hope you have some overloads for this method. 7 (!) parameters, this is a lot. You should try to reduce them and in fact you can hide at least three.

If you make it an extension for the SqlConnection then you'll have one parameter less that you have to specify.

If you use TransactionScope then you can get rid of the second parameter, the SqlTransaction.

If you write two more helper methods (ExecuteQueryAsync & ExecuteStoredProcedureAsync) that call this method, then you can get rid of the CommandType parameter.

So no you just have four parameters left that you must specify: commandText, cancelltionToken & commandTimeout & parameters.


DBSCAN in C++ for general and Android use

Naming things

Why you have all caps function name?

Why you have variable with capital letter in expandCluster()?
At first I thought it is template parameter i miss.

Use auto more often:

// looks ugly
for (node<T>*& n : neighbourhood) {
}

// looks better
for (auto & n : neighbourhood) {
     // adjust for * here
}

// or you can do with using
using mynode = node<T>;

// still looks better
for (mynode* & n : neighbourhood) {
}

DBSCAN()

Make this a type:

template<class T>
using something = std::vector<cluster<T>>

Why you pass dataset_size by reference?

size_t is as big as the pointer, but there will be additional hidden dereference that will slow down the execution.
keep the const, remove &

size_t const dataset_size

Do the same for all non class parameters.

dataset

probably I am wrong, but if you type this:

T* const& dataset

like this:

const T* dataset

will be same, but more readable? Not sure what T is. If T is a container or array, why not just:

const CONTAINER dataset

Why you pass C like function pointers?

Do it with functor class. Or with std::function.

I am not very experienced with this, so I will do it with functor, but will add it into template parameters.

expandCluster()

more or less similar comments.


The conversion

Your program does not produce the correct output in all cases.

10000/3 produces 33{33.3} instead of 3333.{3}.

The reason is that in

int position = remaindersList.indexOf(numerator) + 2;

you assume that the integer part of the fraction is exactly one digit.
This can be (e.g.) solved by remembering the string length right after the integer part has been build:

StringBuilder result = new StringBuilder(whole + ".");
int initialLength = result.length();

120/999 produces 0.120 instead of 0.{120}

The reason is that in

if (result.charAt(result.length() - 1) != '0' && showRepeatingGroup)

the last fraction digit is checked as indicator if the fraction is
repeating or not. This does not work, you have to check if
numerator becomes zero.
2/5 produces 0.40 instead of 0.4

The reason is that you only check for a repeating remainder, but not
if the numerator becomes zero. Therefore an additional 0 is appended
to all non-repeating fractions.

Instead of a (ordered) hash set for the reminders which is converted
to a list later, I would use an (array) list in the first place.
Then you can check for repeating remainders and remember the position
to insert the group markers at the right place.

Other small things: The cast in

int whole = (int)numerator / denominator;

is not necessary, and

numerator = (numerator - (whole * denominator)) * 10;

can be simplified to

numerator = (numerator % denominator) * 10;

Taking all this into account, the divide() function becomes

public static String divide(int numerator, int denominator, boolean showRepeatingGroup)
{
    int whole = numerator / denominator;
    numerator = (numerator % denominator) * 10;

    StringBuilder result = new StringBuilder(whole + ".");
    int initialLength = result.length();

    List<Integer> remainders = new ArrayList<Integer>();
    int repeatingPos = -1;

    while (numerator > 0 && repeatingPos == -1) {
        remainders.add(numerator);
        whole = numerator / denominator;
        numerator = (numerator % denominator) * 10;
        result.append(whole);
        repeatingPos = remainders.indexOf(numerator);
    }

    if (repeatingPos >= 0 && showRepeatingGroup) {
        result.insert(initialLength + repeatingPos,  "{");
        result.append("}");
    }

    return result.toString();
}

But what I don't like is that the calculation of the fractional digits
is mixed with the conversion to a string. If we define a dedicated
DecimalFraction class then the two tasks can be separated clearly:

class DecimalFraction {
    int wholePart;      // Integer part
    List<Integer> fractionDigits; // Fractional digits
    int repeatingAt;    // Position of first repeating digit, or (-1)

    DecimalFraction(int numerator, int denominator) {
        wholePart = numerator / denominator;
        numerator = (numerator % denominator) * 10;
        fractionDigits = new ArrayList<Integer>();
        repeatingAt = -1;

        List<Integer> remainders = new ArrayList<Integer>();
        while (numerator > 0 && repeatingAt == -1) {
            remainders.add(numerator);
            int whole = numerator / denominator;
            numerator = (numerator % denominator) * 10;
            fractionDigits.add(whole);
            repeatingAt = remainders.indexOf(numerator);
        }
    }

    String toString(boolean showRepeatingGroup) {
        StringBuilder result = new StringBuilder(wholePart + ".");
        for (int i = 0; i < fractionDigits.size(); i++) {
            if (showRepeatingGroup && i == repeatingAt) {
                result.append("{");
            }
            result.append(fractionDigits.get(i));
        }
        if (showRepeatingGroup && repeatingAt >= 0) {
            result.append("}");
        }
        return result.toString();
    }
}

This can now be used as

DecimalFraction dfrac = new DecimalFraction(numerator, denominator);
System.out.println("Result: " + dfrac.toString(true));

The main program

As already mentioned in a comment, the slash does not need a pattern group:

Pattern p = Pattern.compile("(\\d+)/(\\d+)");

The code duplication in the "read until input is valid loop" can be
avoided by using a do {  } while() :

Scanner in = new Scanner(System.in);
Matcher m;
do  {
    System.out.print("Enter a fraction in the form x/y: ");
    String input = in.nextLine();
    m = p.matcher(input);
} while (!m.matches());
in.close();

And finally, I don't see why the variables are called top/bottom
instead of numerator/denominator:

int numerator = Integer.parseInt(m.group(1));
int denominator = Integer.parseInt(m.group(2));

DecimalFraction dfrac = new DecimalFraction(numerator, denominator);
System.out.println("Result: " + dfrac.toString(true));


The only thing I can see is moving the related/cleaned posts method into an instance method on Micropost. I'm also not sure what the implementation of Micropost.tagged_with is like, but I bet that could be moved into an instance method. Without that, I might suggest:

class Micropost < ActiveRecord::Base
  def cleaned_related_posts(limit = -1)
    posts = Micropost.tagged_with(tag_list, :on => :tags, :any => true).reject { |p| p == self }
    posts = posts.take(limit) if limit > 0
    posts
  end
end

Then your controller becomes:

def show
  @micropost = Micropost.find(params[:id])
  @tags = @micropost.tag_counts_on(:tags)
  @responses =  @micropost.responses
  @response = current_user.responses.build if member_signed_in?
  impressionist(@micropost)
  @cleaned_related_posts = @micropost.clean_related_posts 5
end

It's not really much of a savings, but it does at least centralize the logic for related posts. This controller isn't really fat to begin with.

  ... RubyMine keeps showing me a warning that the controller should call only one method.

That's just plain silly. IDE suggestions should be taken with a grain of salt (and a wedge of lime, and a shot of tequila).


Code Vita: Form the maximum possible time in the HH:MM:SS format using any six of nine given single digits

Bugs

Your program produces these erroneous results:

0,5,5,5,5,5,5,5,9 → Impossible (should be 09:55:55)
0,2,5,5,5,5,5,5,5 → Impossible (should be 20:55:55)

Due to tests like if hrs[0], if hrs[1], if mins[1], and if secs[1], hours, minutes, or seconds is a multiple of 10, or if the hour starts with 0.
2,2,4,4,4,4,4,4,7 → 24:47:44 (should be 22:47:44)

The challenge states that 24:00:00 is the upper bound.  The correct answer, 22:47:44, demonstrates that a naïve greedy algorithm is not sufficient to solve this problem.  You might optimistically select 24 for the hour (which would work for input such as 0,0,0,0,2,4,9,9,9).  However, for the input 2,2,4,4,4,4,4,4,7, you should then find that there is no valid minute if you pick 24 as the hour, and you would need to backtrack and try 22 for the hour.

Algorithm

There is no need to implement bubbleSort.  Just call sorted(seq_a, reverse=True).  (By PEP 8 naming conventions, the function should be named bubble_sort.)

Your code is repetitive: you write a similar for loop to handle each of the six digits.  You should generalize them to be handled by one loop, which accepts different upper limits for each digit.  Note that you use <= tests for most of those loops, but < 6 for some loops — the inconsistency is confusing.

Suggested solution

I would define a placewise_max function to generalize all of your loops, then call it with three limiting template strings.  Instead of loops with break statements, though, I would use next() with a generator expression.

Note that there is no need to parse each character as a numeric digit: ASCII comparison will work just as well.

def placewise_max(max_template, pool):
    """
    Try to form the lexicographically greatest string from the characters in
    the pool, where the character in each position of the output does not
    exceed the character at the corresponding position in the template.
    Return the empty string if any position cannot be filled.

    >>> placewise_max('91210', list('02301'))
    '31200'
    >>> placewise_max('elmo', 'abcdefghijklm')
    'elmk'
    >>> placewise_max('elmo', 'limo')
    ''
    """
    pool = sorted(pool, reverse=True)
    output = []
    try:
        for t in max_template:
            char = next(c for c in iter(pool) if c <= t)
            pool.remove(char)
            output.append(char)
        return ''.join(output)
    except StopIteration:   # next() failed to pick from the pool
        return ''

def max_time(digits):
    best = max(
        placewise_max('240000', digits),
        placewise_max('235959', digits),
        placewise_max('195959', digits)
    )
    if best and (best != '000000'):
        return '{0}{1}:{2}{3}:{4}{5}'.format(*best)

if __name__ == '__main__':
    print(max_time(input().split(',')) or 'Impossible')

Educational tips

The solution above uses some rather advanced techniques, and may be overwhelming for a beginner.  However, I would point out an essential next step for improving your coding skills.

It is critical to learn to write functions, each with a clearly defined purpose, that accept parameters, return results, and use no global variables.  Document the purpose, parameters, and outputs in a docstring, as I've done.  That will force you to package your code into small, reusable chunks.  For example, can you write a function that accepts a string (or list) of characters, and that returns a tuple with two items — the best possible hour that can be formed from those characters, and all the leftover characters that were not used to form the hour?

Defining a function is necessary to solve this problem correctly, because, as I've pointed out above, a correct solution requires some trial and error.  If you are unable to reuse the code that performs the trials, then you will end up writing if-else statements to handle all of the failure cases, and it's going to be a huge mess!


Fahrenheit and Celsius converter in Rust

The first thing I always do is running clippy.

You will catch some things that are not neccessary, e.g.

fn main() -> () can be reduced to fn main()
let t = String::from(convert_type); is simply let t = convert_type

The bad things are

c * (9 / 5) which is always c because of integer arithmetic. You probably want f64::from(c) * (9.0 / 5.0)
same for (f - 32) * (5 / 9) should be (f64::from(f) - 32.0) * (5.0 / 9.0)) as i32

You may want to add some unit-tests to your program to verify that ctof and ftoc actually work.


Best practice of HTML DOM template in javascript

Personally I would create loops for this, it's very unreadable at the moment and you are repeating yourself a lot. Remember the DRY rule (don't repeat yourself). Also if you do it via loops it's easier to maintain and change in the future.


Your solution looks pretty good. However, a few details can be changed to make your code more pythonic :

Unused variable

You can use _ to name a variable whose value is not used. In your case, it applies to the first loop variable x.

List comprehension

You can rewrite your initialisaion of rockList abusing list comprehension :

rockList = [set(raw_input())
    for _ in xrange(int(raw_input()))]

Simplifying the logic

At the moment, for each element in the first set, you look in how many other sets it appears to know if it is a gem. You can make things clearer by considering that by default it is a gem except if we don't find it in one of the other sets (and in that case, we can stop looping) :

for x in rockList[0]:
    is_gem = True
    for y in rockList[1:]:
        if x not in y:
            is_gem = False
            break
    if is_gem:
        gemElement += 1

Using Python good stuff

Using Python all builtin, we can write this all(x in y for y in rockList[1:]).

You can extract rockList[1:] to call it only once (note that the cute way to write this in Python 3 would be to use extended iterable unpacking). Your code becomes :

gemElement = 0
other_rocks = rockList[1:]
for x in rockList[0]:
    if all(x in y for y in other_rocks):
        gemElement += 1
print gemElement

Now, you can see that we can easily get the actual list of gems doing :

gems = (x for x in rockList[0]
    if all(x in y for y in other_rocks))

This is not an actual list but a generator expression, you'll need to call list(gems) if you want to see an actual list but we don't really care about the list, we just need the number of elements : len(list(gems)) or sum if you don't want to build an intermediate list in memory.

The code is now :

rockList = [set(raw_input())
    for _ in xrange(int(raw_input()))]
other_rocks = rockList[1:]
print sum(1 for x in rockList[0]
    if all(x in y for y in other_rocks))

One step back from the code

The problem we are trying to solve is linked to a common problem : computing the intersection of multiple sets. It is a generic enough problem so that we can google it and find this answer for instance.

Making the solution as concise as possible, one can write :

print len(set.intersection(*[
    set(raw_input())
    for _ in xrange(int(raw_input()))]))


strend, function that checks the occurence of a pattern at the end of a string

I see no point in avoiding the use of Standard Library functions.  Learning to
use them is part of becoming a proficient C programmer.  Hence using strlen
is good and reinventing strcmp or memcmp, as you have done, is bad.  Making the return
value unsigned is just extra typing/noise and achieves nothing.  Here is a
simplified version:

int strend1(const char *str, const char *pattern)
{
    size_t plen = strlen(pattern);
    size_t slen = strlen(str);
    return (plen <= slen)
           && !memcmp(pattern, str + slen - plen, plen) ? 1 : 0;
}

Note that the parameters are const.


Implement this interface in all of your Dto where it needed:

interface ICommonDtoStuff<T>
{
    bool IsSelected { get; }
    T ID { get; }
}

Then you can create a method like this:

public IList<T> GetSelectedResults<T, U>(IEnumerable<U> scores) where U : ICommonDtoStuff<T>
{
    return scores.Where(x => x.IsSelected).Select(x => x.ID).ToList();
}

As extension method:

public static class Extensions
{
    public static IList<T> GetSelectedResults<T>(this IEnumerable<ICommonDtoStuff<T>> scores)
    {
        return scores.Where(x => x.IsSelected).Select(x => x.ID).ToList();
    }
}


Displaying content based on the current time

You are repeating a lot of HTML, which I guess you know could be condensed down, you can also make use of elseif this way it will execute the first TRUE statement and skip the rest.

If there are no matches, for breakfast, lunch, dinner we can assume it must be late night, as there are no more hours left in the day. As this is the case we can just } else { for the last statement.

I have added a check for $row_count as we can never guarantee there will be results returned

<?php

date_default_timezone_set("Europe/London");

$currentTime = date('Hi');
$breakfastStart = "0200";
$breakfastEnd = "1129";

$lunchStart = "1130";
$lunchEnd = "1559";

$dinnerStart = "1600";
$dinnerEnd = "2129";

$lateStart = "2130";
$lateEnd = "0159";

// set up your variables
$rows = $field_key = $field_title = false;

// is it breakfast time?
if( $currentTime >= $breakfastStart && $currentTime <= $breakfastEnd )
{

    // if it is, set the field key and title
    $field_key = 'breakfast';
    $field_title = 'Breakfast';

    // if not, is it lunch time?
} elseif( $currentTime >= $lunchStart && $currentTime <= $lunchEnd )
{

    $field_key = 'lunch';
    $field_title = 'Lunch';

    // if not, is it dinner time?
} elseif( $currentTime >= $dinnerStart && $currentTime <= $dinnerEnd )
{

    $field_key = 'dinner';
    $field_title = 'Dinner';

    // if not, lets assume its late night
} else {

    $field_key = 'late_night';
    $field_title = 'Late Night';

}

$rows = get_field( $field_key , 41190);
$row_count = count($rows);
$i = rand(0, $row_count - 1);

// if we have some rows..
if( $row_count )
{
?>

<?=$field_title?>

        <?php echo $rows[ $i ]['dish_name']; ?>

       <?php echo $rows[ $i ]['dish_description'];  ?>

        Served<?php echo $rows[ $i ]['time_served'];  ?>

<?php
}


I can't comment on the specifics of how efficient your algorithm is, but i can comment on something that is probably more important - assuming you have enough computing power:

Readability and Understandability

if you didn't know anything about Mesh code above, it is very difficult to understand. this means that if you were to look at it in 12 months - would you understand it? this is very important when writing code.

Code

Generally speaking be very suspicious of "if" statements. Whenever you see one you gotta ask: why is that there? if you don't have a good reason, then it might be better of to extract a class and use polymorphism to do the same thing. that way, conditional statements are somewhat isolated from behaviour. that makes things easier to change and somewhat easier to code, but it does come at a price.

Methods

You can hide away some implementation in methods. you've got some methods that are very long that it's not easy for someone unfamiliar with what you're trying to do to make sense of it.

int[] triangles;
if (mesh.triangles.Length == 0)
{
    // there are currently no tiles so create new array match tile count
    triangles = new int[tiles.Count * 6];
}
else
{
    // we already have some tiles so expand the existing array
    triangles = new int[mesh.triangles.Length + (tiles.Count * 6)];
}

you can turn the above into this:

int[] triangles = GetTriangles();

and hide everything in that method. it would already dramatically improve readability

Update

A picture is worth a million words! I can sort of conceptualise what you are trying to do.

Unfortunately i can't comment on the best OOP way because i have a very incomplete pictures but something like this would certainly give you ideas on how to structure code to make it more readable. Without altering what it does.

Secondly - tests - i'm gonna guess that you have written tests for this? if you did then tests will force you to write code more systematically so i highly recommend adding tests.

here is just some basic cutting and pasting - i hope it helps.

Performance

btw - your algorithm looks good enough. but be warned, this type of looping can slow things done if mapLength and width gets too large.

for (int j = 0; j < mapLength; j++)
    {
        for (int i = 0; i < mapWidth; i++)
        {
.....}}

using System.Collections.Generic;
namespace practiceTest
{
    internal class UnityMesh
    {
        private Mesh mesh;
    private void Awake()
    {
        Mesh mesh = CreateMesh();
        this.mesh = mesh;
    }

    /// <summary>
    /// Generates this instance - i don't like the name of this method. it's way too vague
    /// </summary>
    /// <returns></returns>
    private Mesh CreateMesh()
    {
        Vector3d vertices = GetVertices();
        Mesh mesh = SetVerticesToNewMesh(vertices);
        return mesh;
    }

    private Mesh SetVerticesToNewMesh(Vector3d vertices)
    {
        GetComponent<MeshFilter>().mesh = mesh = new Mesh();
        mesh.name = "Floor Grid";
        mesh.MarkDynamic();
        mesh.vertices = vertices;

        return mesh;
    }

    /// <summary>
    /// Gets the vertices.
    /// </summary>
    /// <returns></returns>
    private Vector3d GetVertices()
    {
        vertices = new Vector3[mapLength * mapWidth * 4];
        int v = -1;

        for (int j = 0; j < mapLength; j++)
        {
            for (int i = 0; i < mapWidth; i++)
            {
                vertices[++v] = new Vector3(i * gridSize, 0, j * gridSize); // bottom left
                vertices[++v] = new Vector3(i * gridSize + gridSize, 0, j * gridSize); // bottom right
                vertices[++v] = new Vector3(i * gridSize, 0, j * gridSize + gridSize); // top left
                vertices[++v] = new Vector3(i * gridSize + gridSize, 0, j * gridSize + gridSize); //top right
            }
        }
    }

    private void Add(List<Vector3> tiles)
    {
        int[] triangles = GetTriangles();

        int index = ApplyTriangleIndices(triangles);

        //apply the new triangles for the tiles the user wants
        index = ApplyNewTriangles(tiles, triangles, index);

        mesh.triangles = triangles;
        mesh.RecalculateNormals();
    }

    private static int ApplyNewTriangles(List<Vector3> tiles, int[] triangles, int index)
    {
        for (int i = 0; i < tiles.Count; i++)
        {
            tri = (int)(tiles[i].z * mapWidth + tiles[i].x) * 4;
            triangles[index++] = tri;
            triangles[index++] = tri + 2;
            triangles[index++] = tri + 1;

            triangles[index++] = tri + 2;
            triangles[index++] = tri + 3;
            triangles[index++] = tri + 1;
        }
        return index;
    }

    private int ApplyTriangleIndices(int[] triangles)
    {
        // get the triangle indices from mesh.triangle and apply them to new array
        int index = 0;
        for (int i = 0; i < mesh.triangles.Length; i++)
        {
            trianglesList.AddRange(mesh.triangles);
            triangles[i] = mesh.triangles[i];
            index = i + 1;
        }
        return index;
    }
}
}


Is it a good practice to wrap datatypes in custom classes?

Too much overhead - nullable types and extension methods seem to give you what you need. The checking you do on your setters will never be executed because an int will never be less than int.MinValue or greater than int.MaxValue to begin with.

Only create wrappers over types where you're adding intrinsic business (or technical) value that your consumers will benefit from. I'm afraid the ExtendedInt example you provide doesn't seem to meet that criteria over int? myInt;


Re-arranging an matrix of numbers to a numeric list

I started writing this before the other answer was posted - it's a good answer.

I would also use a dictionary because dictionaries cannot have duplicate keys

Option Explicit

Private Sub MatrixToColumn()

    Dim myMatrix As Range
    Set myMatrix = Range("A1:E5")
    Dim myDictionary As Object
    Set myDictionary = CreateObject("Scripting.Dictionary")
    Dim myCell As Range
    Dim rowNumber As Long
    rowNumber = 1
    Dim Key As Variant

    For Each myCell In myMatrix
        If Not IsEmpty(myCell) Then myDictionary(myCell.Value) = 1
    Next

    If myDictionary.Count > 1 Then
       For Each Key In myDictionary.keys
            Cells(rowNumber, 10) = Key
            rowNumber = rowNumber + 1
       Next
    End If
End Sub

Now, to review your code.

Indenting, none of your code is indented. It's good practice to indent all of your code that way Labels will stick out as obvious.
Sub Test1 - I know you're just testing, but that's a very bad name for a sub.
Call - You don't need to Call subs, it's obsolete. Instead just use Sub argument, argument
Worksheets("List").Activate - Be sure to avoid things like .Activate - it just slows the code down by needing to fiddle with the spreadsheet while doing everything else behind the scenes. There's a good question on StackOverflow addressing this - https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros .
lastRow = Range("A1").End(xlDown).Row this isn't a great way to do this, the standard way is lastRow = Cells(Rows.Count, 1).End(xlUp).Row - see this answer on SO by a very talented excel MVP
Everything you're doing on the sheet can be done in the code, in a dictionary or at least in an array. That increases speed by a significant amount
Dim Rng - it's a bad name and it doesn't follow Standard VBA naming conventions which hascamelCase for local variables and PascalCase for other variables and names.
Variable names - give your variables meaningful names. Instead of Rng you could make it myMatrix or something similar.

For future reference:

If Rng = Rng.Offset(1, 0) And IsEmpty(Rng.Value) = False Then
Rng.Delete Shift:=xlUp

ElseIf Rng <> Rng.Offset(1, 0) And IsEmpty(Rng.Value) = False Then
i = i + 1
ElseIf Application.WorksheetFunction.CountA(Rng) = 0 Then
i = i + 1
Else: i = i + 1

End If

This piece of code can be optimized

If Not IsEmpty(Rng.Value) Then
    If Rng = Rng.Offset(1) Then Rng.Delete shift:=xlUp
Else: i = i + 1
End If

Your While loops aren't the preferred way in VBA; instead use a For loop-

For i = 1 to lastRow
Next

If IsEmpty(Rng.Offset(0, 1).Value) = False Then

I prefer to use a Not instead of If False because If usually checks for True

If Not IsEmpty(rng.offset(,1)) then

Instead of calculating lastRow twice, just pass it from one sub to the other

Private Sub RemoveDuplicates2(ByVal lastRow as Long)

Now you can

RemoveDuplicates2 lastRow

You could even pass your range as well

Private Sub RemoveDuplicates(ByVal lastRow as Long, ByVal myRange as Range)

This isn't great either

ActiveWorkbook.Worksheets("List")

Worksheets have a CodeName property - View Properties window (F4) and the (Name) field can be used as the worksheet name. This way you can avoid Sheets("List") and instead just use List.


onResize and onLoad handlers to toggle mobile layout

Your code is mainly about this test:

if (window.innerWidth >= MIN_WIDTH_BREAKPOINT)

You shouldn't be doing this using JavaScript to do this at all. Width-dependent layout is exactly what CSS media queries are for.

Furthermore, I would caution you against activating the mobile layout based on the width. This will break the "Request Desktop Site" feature in iOS Mobile Safari, which uses User-Agent switching instead.


Consider alternatives to linked lists

You are wondering whether this is the most efficient way to implement a stack. If you store ints, then the overhead of maintaining a linked list is quite large. Another option would be to keep the integer values in a dynamically allocated array. That way, the only other piece of information you need to store is the size of your stack. The drawback of an array is that if you grow the stack, you have to grow the memory for it, which can be expensive, but if you do this in a smart way the overhead will probably still be less than with linked lists.

You can also go for a hybrid approach: have struct NODE contain a fixed number of ints, say 8 or 16, and only allocate another struct NODE when the previous one is full.

Don't use all-capital names for types

All-capital identifiers are normally used for macros. It's always best to follow conventions. When defining a new struct, I recommend this pattern:

typedef struct foo {
    ...
} foo_t;

Avoid recursion if it is easy to do so

Your function display() cleverly uses recursion to display all the elements in the stack. However, without any optimizations enabled, if your stack is very large, this will actually cause a lot of real stack space to be used! With optimization enabled, the compiler will most likely perform a tail call optimization, but in this case you can easily rewrite the function as a loop:

void display(node *head)
{
    for(node *it = head; it; it = it->next)
        printf("%d\n", it->data);
}

Ensure a pointer is not NULL before dereferencing it

Your functions pop() and Top() blindly dereference the pointer top. If you would call these functions when the stack is empty, your program will crash.

Rename the variable top

This variable is effectively a private variable that you shouldn't access directly, only via the stack manipulation functions that you created (push(), pop() and Top()). Already there is the issue that it has the same name as the function Top(), and while C is case-sensitive, this solution is not pretty. Rename the function Top() to top(), so it matches the other functions, and rename the pointer top to something like stack_top or top_.


Out-of-bounds access: an array

Image graph[vertices];

has vertices entries, starting with index 0, with the largest valid index being vertices - 1. The loop

for(int i = 1; i<= vertices; i++)

touches graph[vertices], which is illegal. A correct (and idiamatic) loop is

for(int i = 0; i < vertices; i++)

Testing for memory correctly released via inducing a segfault is, to put it mildly, unconventional. You are not even guaranteed to get one.
Crawling the list is a waste of time. It is much simpler to prepend  the newly created node at the head of the list:

void add_adj_node(Image *graph, int src, int dest, bool directed)
{
    adjList * node = create_node(dest);
    node->next = graph[src].head;
    graph[src]head = node;
}

Recursive invocation of add_adj_node is confusing. I recommend to have a helper function do_add_adj_node and invoke it like this:

void add_adj_node(Image *graph, int src, int dest) {
    do_add_adj_node(graph, src, dst);
    do_add_adj_node(graph, dst, src);
}


Collecting data from General Ledger accounts lines

Here's a suggestion for simplifying your code by refactoring a bit and copying out the common part to a separate sub.  Also sets values directly in place of copy/paste.

This could be refactored completely to (eg) read the values to be matched from a table on a worksheet, along with the destination for each matched row.

Sub Table9052()

    'use constants for fixed values
    Const Locker As String = "9052 Electronic Lockers"
    Const GC As String = "9042 Dunkin Donuts Gift Card"
    Const MBD As String = "MERCHANT BANKC*"
    Const DDSV As String = "DD STORED VALU*"
    Const SS As String = "STARBUCKS STOR*"

    Dim i As Long '<< use long in place on Integer
    Dim ColA As Range, ColF  As Range, ColK  As Range, ColP As Range, ColU  As Range

    Dim wsA As Worksheet: Set wsA = ThisWorkbook.Sheets("QA Data A")
    Dim wsK As Worksheet: Set wsK = ThisWorkbook.Sheets("QA Data K")
    Dim wsT As Worksheet: Set wsT = ThisWorkbook.Sheets("Tables")

    Dim Eval, rw As Range

    'set the starting points for each of the destination tables
    With wsT
        Set ColA = .Cells(3, "A")
        Set ColF = .Cells(3, "F")
        Set ColK = .Cells(3, "K")
        Set ColP = .Cells(3, "P")
        Set ColU = .Cells(3, "U")
    End With

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False

    For i = 6 To wsA.Range("C65536").End(xlUp).Row
        Set rw = wsA.Rows(i)
        Select Case rw.Cells(4).Value
            Case Locker: CopyRow rw, ColA
            Case GC: CopyRow rw, ColP
        End Select
    Next i

    For i = 6 To wsK.Range("C65536").End(xlUp).Row
        Set rw = wsK.Rows(i)
        Eval = rw.Cells(4)

        If Eval Like MBD & "*" Then CopyRow rw, ColF
        If Eval Like DDSV & "*" Then CopyRow rw, ColK
        If Eval Like SS & "*" Then CopyRow rw, ColU

    Next i
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

'extract out the common code to a separate sub
'   copy values and advance to next row
Sub CopyRow(rw As Range, cDest As Range)
    cDest.Resize(1, 4).Value = _
            Array(rw.Cells(3).Value, rw.Cells(4).Value, _
            rw.Cells(5).Value, rw.Cells(7).Value)
    Set cDest = cDest.Offset(1, 0) 'next row...
End Sub


UserScript to Highlight tab for queue item

How does the es-6 usage look? What would you change and/or code differently?

1. Arrow Functions
I would personally recommend using arrow functions where you have not to stay consistent with the ES6 usage throughout your code.
Example:
;(function() {

... can be changed to:
;(() => {

Additionally, parenthesis are optional when only one parameter is given.
Example:
document.addEventListener('click', (event) => timeout ...

... can be changed to:
document.addEventListener('click', event => timeout ...

2. Constant Arrow Function Expressions
Since it does not appear that you have any intention of overwriting your functions, I would recommend using function expressions defined as constants, rather than function declarations.
Example:
function updateTitle(showAsterisk = false) {

... can be changed to:
const updateTitle = (showAsterisk = false) => {

3. Don't Use var
If you can use let or const, use them instead.
Example:
var titleMatches = document.title.match(/^([\W]{1})Review/);

... can be changed to:
const titleMatches = document.title.match(/^([\W]{1})Review/);

4. The window. Prefix is Unnecessary
You do not need to use the window prefix on window.setTimeout, window.clearTimeout, or window.location.
Example:
window.clearTimeout(timeout);

... can be changed to:
clearTimeout(timeout);

Final Result
Ultimately, the final result of the changes I would make would look like the following:
// ==UserScript==
// @name         Highlight active review
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Bring attention to the user when a post is up for reviewing
// @author       Sam Onela
// @match        https://codereview.stackexchange.com/review/*
// ==/UserScript==

;(() =>
{
    'use strict';

    const INITIAL_CHECK_TIMEOUT = 1500;
    const INTERVAL_DELAY        = 400;
    const RELOAD_DELAY          = 6500;
    const CLICK_CHECK_DELAY     = 6000;
    const ticks                 = [
        '⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'
    ];

    let timeout = setTimeout(check, INITIAL_CHECK_TIMEOUT);
    let interval;

    const updateTitle = (showAsterisk = false) =>
    {
        let titleMatches = document.title.match(/^([\W]{1})Review/);

        if (titleMatches && titleMatches.length > 1)
        {
            const index    = ticks.indexOf(titleMatches[1]);
            document.title = document.title.replace(titleMatches[1], ticks[( index + 1) % ticks.length]);
        }

        else
        {
            document.title = (showAsterisk ? '*' : ticks[0]) + document.title;
        }
    };

    const check = (clickHandlerAdded = false) =>
    {
        if (timeout)
        {
            clearTimeout(timeout);
            timeout = 0;
        }

        if (window.location.pathname.match(/\d+/)) // drilled in to a review item
        {
            updateTitle(true);

            if (!clickHandlerAdded)
            {
                document.addEventListener('click', event => timeout = setTimeout(check, CLICK_CHECK_DELAY, true));
            }
        }

        else //add spinner animation and then reload
        {
            updateTitle();

            if (interval === undefined)
            {
                interval = setInterval(updateTitle, INTERVAL_DELAY);
            }

            setTimeout(_ => window.location = window.location, RELOAD_DELAY);
        }
    };

})();

Hope this helps!


Consider this:

for (int i = 0; i < values.length; i++) {
    if (i!=0 && values[i] < values[i - 1]) {

i starts from 0, and then right after you use a condition i!=0. You could simplify to:

for (int i = 1; i < values.length; i++) {
    if (values[i] < values[i - 1]) {

Consider this:

if (values[i] < values[i - 1]) {
    for (int j = i; j >= 1; j--) {
        if (values[j] < values[j - 1]) {
            // ...
        } else break;

Notice that j starts from i, and you have the same if immediately inside the loop, otherwise break. In other words, you don't need that outer if, because you run the same thing immediately inside the loop.

Consider this:

for (int j = i; j >= 1; j--) {
    if (values[j] < values[j - 1]) {
        ...
    } else break;

an equivalent but shorter and more traditional way to write the same thing:

for (int j = i; j >= 1 && values[j] < values[j - 1]; j--) {
    ...
}

Putting it all together:

for (int i = 1; i < values.length; i++) {
    for (int j = i; j > 0 && values[j] < values[j - 1]; j--) {
        int temp = values[j - 1];
        values[j - 1] = values[j];
        values[j] = temp;
    }
}

We have arrived at the pseudo algorithm of insertion sort in wikipedia ;-)

I recommend using unit tests to check your implementations instead of printing text to the console and checking with your eyes. For example:

public Integer[] sort(Integer[] orig) {
    Integer[] values = orig.clone();
    for (int i = 1; i < values.length; i++) {
        for (int j = i; j > 0 && values[j] < values[j - 1]; j--) {
            int temp = values[j - 1];
            values[j - 1] = values[j];
            values[j] = temp;
        }
    }
    return values;
}

@Test
public void testExamples() {
    Assert.assertArrayEquals(new Integer[]{3, 4, 5}, sort(new Integer[]{5, 4, 3}));
    Assert.assertArrayEquals(new Integer[]{3, 4, 5}, sort(new Integer[]{5, 3, 4}));
    Assert.assertArrayEquals(new Integer[]{3, 4, 5}, sort(new Integer[]{3, 5, 4}));
}

Running this is just as easy as running a main method. This approach also encourages decomposing your problems to elementary operations. In this case I had to extract the sorting logic to its own method to be easier to test. In the end, you will naturally have multiple methods, which is a good thing, at virtually no extra cost.


Citadel's VisualEncrypt and VisualDecrypt

The way you handle the first element as a special case is cumbersome: you're basically unrolling the first iteration of the loop.  You could just initialize value = 0 so that the first XOR just copies the input to the output.

template <class InputIterator, class OutputIterator>
OutputIterator VisualEncrypt (InputIterator begin, InputIterator end, OutputIterator destination)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    T value = 0;
    while (begin != end) {
        value ^= *begin++;
        *destination++ = value ;
    }

    return destination ;
}

template <class InputIterator, class OutputIterator>
OutputIterator VisualDecrypt (InputIterator begin, InputIterator end, OutputIterator destination)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    T value = 0;

    while (begin != end) {
        T temp = *begin++;
        *destination++ = value ^ temp ;
        value = temp ;
    }

    return destination ;
}

Alternatively, use a for-loop, which results in slightly more compact code and gets the pesky side-effect ++ operators out of the way.

template <class InputIterator, class OutputIterator>
OutputIterator VisualEncrypt(InputIterator begin, InputIterator end, OutputIterator destination)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    for (T value = 0; begin != end; ++begin, ++destination) {
        *destination = (value ^= *begin);    // <-- Probably controversial one-liner
    }

    return destination;
}

template <class InputIterator, class OutputIterator>
OutputIterator VisualDecrypt(InputIterator begin, InputIterator end, OutputIterator destination)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    for (T value = 0; begin != end; ++begin, ++destination) {
        T temp = *begin;
        *destination = value ^ temp;
        value = temp;
    }

    return destination;
}


Constant Time implementation of String Uniqueness Algorithm

Critique

You have to describe something for which your input scale, which in this would be the length of your string, so in this regard your implementation is still linear. The part where you try every single possible index for storing a specific character is overkill, since it is often possible to directly calculate it through some kind of hashing. It would therefore be much faster to use a dictionary or the equivalent.

Alternative

We can solve this problem very simply for a more general case (any sequence of items is unique) by turning it into a set:

is_unique = lambda xs: len(xs) == len(set(xs))

Note that you might want to do some extra work if you want to only have printable characters, such as by applying a filter first.


Three ways to add pronoun method/property to gendered class in Python

I usually try to use data structure over code whenever it's possible.
It usually make things shorter, easier to read and easier to update.

If I had to write such a thing, I'd probably write something like (untested code but just to show the idea) :

pronouns = {
    'male' => ("he","his"),
    'female' => ("she", "her")
}

def pronoun(self, possessive=False):
    return pronouns.get(self.gender, default=("they","their"))[possessive]

If we could be sure that self.gender has only 3 different values, the default value could be put in the pronouns dictionnary straightaway (associated to "plural" for instance).

Different variations could be written. I guess one could use defaultdict to ensure that we always retrieve the default value. I don't like this solution that much as the dictionnary would get bigger as we try to retrieve using invalid keys.

I don't know if there's a (simple) way to have a dictionnary which returns a default value when the key is not present without updating the dictionnary but I'd be interested in such a thing.


Recursive memory hog!!

I have to say that this is not at all a practical way to zip two arrays.

Recursive functions are huge memory hogs in JS if done badly

In Javascript calling a function adds a minimum of about 1 - 1.5K to the call stack, and you create copies each array of each call, ouch..

Test

I ran your function giving it two 8Mb array (1,000,000 numbers each) and it crashed Chrome. Something I would expect to do using a function like zip.

Crashed at 0.01% complete

Canary 65 devtools has a live performance monitor, so I ran that and I watched memory climb in less than a second to 1GB befor the browser interrupted and paused the code. The heap is full and the function was only 97 iterations in (approx 0.01% complete).

Why the memory usage?

Your use of Array.slice is the reason. Slice creates a shallow copy of each array. So if you have an array of size 100 and slice at 1 you now have two arrays for a total of 199 items.

Lets follow the recursion with 2 3 itemed arrays

function zip(p,q) {
  if( p.length > 1 || q.length > 2) {
    return ([[p[0],q[0]]]).concat(zip(p.slice(1),q.slice(1)));
  } else {
    return ([[p[0],q[0]]]);
  }
}

Make the call

zip([1,2,3],[4,5,6]);

zip(p.slice(1),q.slice(1));       // create 2 copies 2 bytes each
>> zip(p.slice(1),q.slice(1))     // create 2 copies 1 bytes each
>> >>  return ([[p[0],q[0]]]);

At this point there are arrays [3,6], [3], [6], [2,3], [5,6], [1,2,3], [4,5,6]

return ([[p[0],q[0]]]).concat( << <<

This is when you hit peek memory use, just before the above return you add another array [1,4,3,6] so you have stored in memory 18 references

return ([[p[0],q[0]]]).concat( <<
End.

Result is an array with 6 references.

Calculating memory use

You memory usage assuming same sized arrays is

len = array.length; // both arrays are the same size

totalReferences = (len / 2) * (len + 1) * 2 + 6

So for 2 array of size 100

(100 / 2) * (100 + 1) * 2 + 6 === 10,106

And for larger

1,000   === 1,001,006
10,000  === 100,010,006
100,000 === 10,000,100,006

How to improve.

Can Tail Call Optimisation (TCO) help?

TCO basically lets you call a function without adding a new context to the call stack. This makes calling a function almost as fast as running inline code. This would be the single best thing to have happened to the language for decades (and its only decades old), if it happened :(.

Javascript ES6 spec has (the very anticipated and needed) TCO but it remains the only unimplemented ES6 feature on Chrome, Firefox, and Edge. Reason?? I believe too many pages are kept running due to call stack overflow error, TCO prevents this and thus a bad recursion function blocks the page rather than throws an error.

Don't hold your breath waiting for TCO, for now its not going to help.

The only solution

In reality without TCO you can not safely do this via recursion. The call stack size is much smaller than the max array size. If you do recursion you would have to limit the array sizes, but even then you can not know how deep you are already in the call stack when you start, so there is no safe way to do this (Yes all recursive functions in javascript are fatally flawed, until TCO)

Quick simple and low memory use.

function zip(a, b) {
    const min = Math.min(a.length, b.length);
    var i, j, c;
    c = [];
    i = j = 0;
    while (j < min) {
        c[i ++] = a[j];
        c[i ++] = b[j ++];
    }
    if (a.length < b.length) { [a, b] = [b, a] }
    while (j < a.length) { c[i ++] = a[j ++] }
    return c;
}


A Java class for calculating size of iterable/array v2

if (data instanceof Collection) {
    return ((Collection<?>) data).size();
}

This looks like it was meant to improve performance for big collections. But, that instanceof will prevent certain compiler optimizations and you will get huge performance hit for smaller collections. It's likely not worth it, as most collections are small. This could be avoided by having separate method for Collections and Iterables.

Universal utilities like this improve neither readability nor performance. I do not see how Size.size(x) is more readable than x.length or x.size(). The only benefit is that you don't have to think which one to use.

I would leave only method for calculating the size of Iterables and use size()/length for collections/arrays.

/**
 * Created by IDEA on 16/11/14.
 */

Such comments aren't really useful.

public class Size {

I would make the class final and the constructor private as there is no reason to extend or instantiate class with only static methods.


Finding the length of the longest streak of ones in any array

I see a number of things that could help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Use only required #includes

The code has a line #include "stdio.h"s that is not needed.  This clutters the code and makes it more difficult to read and understand.  Only include files that are actually needed.

Provide main

It may just have been a cut and paste error, but this appears to be the contents of a main function, even though main does not appear.

Use appropriate names for constants

The constants size and ONE are a bit too generic and likely to be used elsewhere.  In fact, this code won't even compile using a current version of gcc because of a name clash with size.

Prefer constexpr to old-style #define

Rather than using a #define for size the code could use a constexpr:

constexpr std::size_t ARRAY_SIZE = 11;

It doesn't make a lot of difference here, but generally the advantage is that the value has an associated type.

Declare variables as late as possible

Rather than using the old C-style of declaring all variables at the top of a function, use the modern C++-style and declare variables as late as possible.  Doing so can sometimes help the compiler figure out register allocation, resulting in faster, smaller code.

Fix your formatting

There are inconsistent spaces at the beginning of lines, inconsistent indentation and inconsistent use of curly braces {}.  Being consistent helps others read and understand your code.

Be careful with signed and unsigned

The code compares an int loop_count with the size of the array.  Is the size of the array ever going to be a negative number?  Probably not.  Therefore, it would be better to declare loop_count to be of type std::size_t.

Fix the bugs

The description says that this code counts ones but the code includes this line:

if((arr[loop_count]&ONE) == ONE)

The use of the operator & in there is doing a binary "and" operation.  That expression would be true if the value is -1 or 5 or any other odd number.  What you probably really want is

if (arr[loop_count] == ONE)

Also, your program only counts the length of the last sequence of contiguous ones.  If you want the maximum length, you'll have to save it.

Simplify your code

The code contains this sequence:

if(continuity)
    sequence_count++;
else
{
    continuity = true;
    sequence_count++;
}

But it could be replaced with this simpler sequence:

sequence_count++;

And then the continuity variable isn't even needed.

An alternative

Here's the code as it might look with all of these suggestions applied:

#include <iostream>

int main()
{
    constexpr std::size_t ARRAY_SIZE {11};
    constexpr int target_value {1};

    int arr[ARRAY_SIZE] = {1, 0, 1, -1, 0, 1, 1, 1, 0, 1, 1};
    unsigned sequence_count = 0;
    unsigned max_sequence = 0;
    for(std::size_t i = 0; i<ARRAY_SIZE; i++) {
        if (arr[i] == target_value) {
            if (++sequence_count > max_sequence) {
                max_sequence = sequence_count;
            }
        } else {
            sequence_count = 0;
        }
    }
    std::cout << max_sequence << std::endl;
}


Change Background Color of ASP:GridView Based On Text

Generally, styling should be handled using client side methods such as using css/javascript so I would recommend you do some brushing up on that side. Never the less I was like you when I first started and just jumped straight into c# so here is a purely c# based solution :).

If it's only ever going to be the first row that needs to be shaded grey you can just reference that row when the binding in complete. The event you're currently subscribing to OnRowDataBound will fire for every row. There is another event that can be accessed once all rows are completed called OnDataBound.

First thing to do would be to register this event in the html markup of your gridview, using the same approach you used to register the OnRowDataBound event.

<asp:gridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnDataBound="GridView1_OnDataBound"></asp:gridView>

Then you can code up the event in your c#.

protected void GridView1_OnDataBound(object sender, EventArgs e)
{
    if(GridView1.Rows.Count > 0) //Check there are rows bound
    {
        var Row = GridView1.Rows[0];// Get The First Row - you may have a header row. If this is the case change 0's to 1's!

        Row.BackColor = System.Drawing.Color.Gray;// Assign the back color
    }
}


I don't see the need for the HasManager property. Either a Manager is assigned, or not. It wouldn't make sense for you to set it to True when there isn't one, or False when there is.

Then just change your Print function to check -

If Not emp.Manager Is Nothing Then
    Debug.Print emp.Name & " is managed by " & emp.Manager.Name
 Else
    Debug.Print emp.Name & " has no manager."

If it was easy to overload the class initialization for employee, I'd say make a name value obligatory, but it's really not a simple task in VBA.

These two properties:

Public Property Get Team() As Employee
    Team = pTeam
End Property

Public Property Let Team(Value As Employee)
    pTeam = Value
End Property

Are passing Objects - why not pass Strings given the team information is handled by a string.


You could use the modulo operator instead of conditions:

static string Encrypt(string toEncrypt, int shift)
{
    const int alphabetLength = 'z' - 'a' + 1;
    char[] buffer = toEncrypt.ToCharArray();

    for (int i = 0; i < buffer.Length; i++)
    {
        char letter = (char)(buffer[i] - 'a'); // Let the `letter` be an offset from 'a'
        letter = (char)((letter + shift) % alphabetLength);
        buffer[i] = (char)(letter + 'a');
    }
    return new string(buffer);
}

Or almost one-liner:

static string Encrypt(string toEncrypt, int shift)
{
    const int alphabetLength = 'z' - 'a' + 1;
    return new string(Array.ConvertAll(toEncrypt.ToCharArray(),
        c => (char)('a' + (c - 'a' + shift) % alphabetLength)));
}


This is indeed interesting challenge!

-- Read after H[
class ReadHList (a :: [*]) where
  readHList :: ReadPrec (HList a)

-- Read after element:
-- ] for nil
-- , readHList for cons
class ReadHListAfter (a :: [*]) where
  readHListAfter :: ReadPrec (HList a)

instance ReadHList '[] where
  readHList = expectP (L.Punc "]") >> return HNil

instance ReadHListAfter '[] where
  readHListAfter = readHList

instance (Read a, ReadHListAfter l) => ReadHList (a ': l) where
  readHList = ...

-- We could use ReadHList (a ': l) as additional constraint,
-- But then we need UndecidableInstances extension
instance (Read a, ReadHListAfter l) => ReadHListAfter (a ': l) where
  readHListAfter = ...

-- Parsing HList is trivial as composing functions!
instance ReadHList a => Read (HList a) where
  readPrec = parens $ do
    expectP (L.Ident "H")
    expectP (L.Punc "[")
    readHList

This way it's a bit more elegant. IMHO.

Compare it to pseudo-codish parsing of lists of known length (aka vectors):

list :: Int -> Parser a -> Parser [a]
list n p =
  token '['
  list' n p

list' :: Int -> Parser a -> Parser [a]
list' 0 _ = token ']' >> return []
list' n p = do
  h <- p
  t <- listTail (n - 1) p
  return (h : t)

listTail :: Int -> Parser a -> Parser [a]
listTail 0 _ = token ']' >> return []
listTail n = do
  h <- p
  token ','
  t <- listTail (n - 1) p
  return (h : t)


Well there is a standard library function: frequences :)

user> (doc frequencies)
-------------------------
clojure.core/frequencies
([coll])
  Returns a map from distinct items in coll to the number of times
  they appear.

Since in Clojure many many types can be converted to sequences, frequencies will work on many types, including strings. In Clojure you can get an amazing amount of work done simply by using the sequence library. So your string-to-letter-hash is actually just an example of frequences.

For your can-play: the same type of thinking applies. Try to resist your first impulse of writing a loop. The Clojure library functions will almost always do the job - the thing that requires training is knowing the library well enough to find a good way to compose the functions.

(defn can-play? [word freqs]
  (every? #(>= % 0) (vals (merge-with - freqs (frequencies word)))))

(updated to comment version: https://gist.github.com/4105644)