Unique random number generation in Swift

Your code made me think of a few improvements I could made: the data workflow is not easy to follow and this complexity is not necessary for this task, and this is what will change in my version. Other than that, I'm just proposing general improvements.

Let's start by listing what we need:

a dedicated class
generate x times a random number
each random number must be unique
each random number has a max value

For this, I start by making a class template:

class EuroMillions {

    var numbers: [Int] = []

    func generateNumbers(repetitions: Int, maxValue: Int) -> [Int] {
        // here, generate a random number x times
        // then populate the 'numbers' array and return it
        return numbers
    }

}

We have what we need: parameters for how many random numbers to generate and a maximum value.

Now how do we populate the array?

First we need to ensure that the maxValue is more or equal the number of repetitions, otherwise the task is not achievable with unique random numbers:

func generateNumbers(repetitions: Int, maxValue: Int) -> [Int] {

    guard maxValue >= repetitions else {
        fatalError("maxValue must be >= repetitions")
    }

    // work to do here

    return numbers
}

We also need to actually generate a random number:

private func random(maxValue: Int) -> Int {
    return Int(arc4random_uniform(UInt32(maxValue + 1)))
}

This will generate a number between 0 and maxValue, the latter included. If you don't want the maxValue being inclusive, remove the + 1.

We also need to check if the generated number is not already in our array.

For this, I've chosen to use a repeat while loop inside the counting loop and to use contains for checking the array:

for _ in 1...repetitions {
    var n: Int
    repeat {
        n = random(maxValue: maxValue)
    } while numbers.contains(n)
    numbers.append(n)
}

We loop x number of times (number of iterations = number of numbers to get). Since we don't need the index we discard it with _.

We prepare an Int, and populate this Int with a random value in a while loop.

The repeat loop generates a number then checks, in the while, if this value is already in the array with .contains.

If the number is not in the array, we break out of the inner loop and add it. If already present we continue generating until we have one that isn't in the array.

Another security check is to set the array to empty before generating, just in case the user would use our method several consecutive times (we could also avoid that by returning the result directly instead of populating an array property, and we'll see that later).

Complete code:

class EuroMillions {

    var numbers: [Int] = []

    func generateNumbers(repetitions: Int, maxValue: Int) -> [Int] {
        guard maxValue >= repetitions else {
            fatalError("maxValue must be >= repetitions for the numbers to be unique")
        }

        numbers = []

        for _ in 1...repetitions {
            var n: Int
            repeat {
                n = random(maxValue: maxValue)
            } while numbers.contains(n)
            numbers.append(n)
        }

        return numbers
    }

    private func random(maxValue: Int) -> Int {
        return Int(arc4random_uniform(UInt32(maxValue + 1)))
    }

}

Usage:

let lottery = EuroMillions()
let numbers = lottery.generateNumbers(repetitions: 6, maxValue: 49)
print(numbers)

Possible result:

  [7, 12, 0, 9, 24, 35]

This was my main answer to your question.

How could we improve this class a bit more, or have fun, or both?

I would add the possibility to choose different lotteries, for example, and have defaults for them (methods prepared with preset values).

We also should set access privileges to methods and properties.

And I also like to have a printable identifier for the class.

For the identifier I like to use CustomStringConvertible which makes the class printable by adding a description:

class EuroMillions: CustomStringConvertible {

    // ...

    public var description: String {
        // return something relevant here
    }

}

And for the different lottery modes I would use an enum:

public enum LotteryMode: String {
    case euroMillions = "Euro Millions"
    case lotto = "Lotto"
}

public class Lottery {

    private var mode: LotteryMode

    public init(mode: LotteryMode = .euroMillions) {
        self.mode = mode
    }

    public func generate() -> [Int] {
        switch mode {
        case .euroMillions:
            return generateNumbers(repetitions: 5, maxValue: 49)
        case .lotto:
            return generateNumbers(repetitions: 6, maxValue: 49)
        }
    }

    // ...

}

Now we make generateNumbers(repetitions:, maxValue:) private because in this version of the class we only use the new preset method generate(), but this is not mandatory, it's just an example.

I also make the array private so that it can't be tempered with from outside, and add a public computed property to get its contents again once generated (since the class keeps state).

Complete code:

public enum LotteryMode: String {
    case euroMillions = "Euro Millions"
    case lotto = "Lotto"
}

public class Lottery: CustomStringConvertible {

    private var numbers: [Int] = []

    private var mode: LotteryMode

    public init(mode: LotteryMode = .euroMillions) {
        self.mode = mode
    }

    public var results: [Int] {
        return numbers
    }

    public func generate() -> [Int] {
        switch mode {
        case .euroMillions:
            return generateNumbers(repetitions: 5, maxValue: 49)
        case .lotto:
            return generateNumbers(repetitions: 6, maxValue: 49)
        }
    }

    private func generateNumbers(repetitions: Int, maxValue: Int) -> [Int] {
        guard maxValue >= repetitions else {
            fatalError("maxValue must be >= repetitions")
        }

        numbers = []

        for _ in 1...repetitions {
            var n: Int
            repeat {
                n = random(maxValue: maxValue)
            } while numbers.contains(n)
            numbers.append(n)
        }

        return numbers
    }

    private func random(maxValue: Int) -> Int {
        return Int(arc4random_uniform(UInt32(maxValue + 1)))
    }

    public var description: String {
        if numbers.isEmpty {
            return "\(mode.rawValue) - No result"
        } else {
            let content = numbers.map { String($0) }.joined(separator: ", ")
            return "\(mode.rawValue) - Result: \(content)"
        }
    }

}

Usage examples:

let euros = Lottery() // or Lottery(mode: .euroMillions)
print(euros)
let eurosNumbers = euros.generate()
print(euros)
print(eurosNumbers)
print(euros.results)

let lotto = Lottery(mode: .lotto)
print(lotto)
let lottoNumbers = lotto.generate()
print(lotto)
print(lottoNumbers)
print(lotto.results)


Simple singleton database connection pool

Your connection pool is not threadsafe / concurrently usable, if you are sure you do not need it to be ignore my points 1. to 3.
Your pool does not offer connection locking (mutual exclusive usage of one Connection object) which is usually implemented by making the connection inaccessible after getConnection() and making it eligible for takeout after calling its close() method. You close the raw connections manually, leaving the pool in a broken state.
This is problematic: https://stackoverflow.com/questions/9428573/
Your counter int might return the same int for two concurrent calls at the same time. Use AtomicInteger / AtomicLong instead.
Your pool does not implement connection testing: Your connections could expire at any time. You need to replace broken Connections with new Connections or your program might receive dead Connection objects!
You might want to implement Closeable to close all connections at once when your application shuts down and clear the instance.
You might want to throw if initializeConnections fails, because what are you supposed to do with a broken object?
Hardcoding URLs that might change is not considered good practice


Converting a Bool to a Bool with an if

if tests Bool values and returns results. You’re using it to return True if the input is True, and False if the input is False:

convertToBool y = if y `mod` 2 == 0 then True else False

But that’s just the identity function. You can remove the if:

convertToBool y = y `mod` 2 == 0

Useless parentheses

random (gen1)
random (gen2)

Generating random Ints rather than the type you wish to get directly

You’re using random to generate an Int. That’s fine if you want an Int—but you want a Bool. Sure, you can calculate a Bool out of one, but random can also give you a Bool directly. This would simplify your implementation.

I feel it’s necessary to point out the dangers of limiting random numbers to a range with modulo. In this case, it’s not actually a problem, but pretend you want to generate a number between 0 and 6, and the random number generator you have gives you numbers between 0 and 9. If you used modulo, you’d map:

0, 6 --> 0
1, 7 --> 1
2, 8 --> 2
3, 9 --> 3
4    --> 4
5    --> 5
6    --> 6

That’s not a very even distribution. The problem arises because 7 and 10 do not share a factor. It’s not relevant to you because you’re trying to generate something in the range 0 to 1 (two values) and two is a factor of the number of values in Int, but it’s something to be aware of nonetheless.

Dependence on mkStdGen

Right now, you let the user pass in a seed that is then passed to mkStdGen. That works, I suppose, but it would be more flexible if you pushed that responsibility to the user, because then the user can create an StdGen however they desire (with, say, getStdGen). Your signature would then look like this:

coinToss3 :: StdGen -> (Bool, Bool, Bool)

You could even change your definition to allow any RandomGen instance:

coinToss3 :: (RandomGen g) => g -> (Bool, Bool, Bool)

Potential cleanup with MonadRandom and Applicative

At your current point in Learn You A Haskell, you haven’t learned about Monad or Applicative yet, so you may want to ignore this for now and take a look at it later, but using MonadRandom and Applicative, your code can be considerably shortened:

import Control.Applicative
import Control.Monad.Random

coinToss3 :: (RandomGen g) => g -> (Bool, Bool, Bool)
coinToss3 = evalRand $ (,,) <$> random <*> random <*> random


Convert length of time to appropriate unit

Here's one approach, using TreeMap.  It looks up your number of milliseconds in a pre-populated map, finds the appropriate entry and does the division.

Just create one of these objects, and call the format method as many times as you need to.

Note that it's not quite right for negative arguments to format - but you might want to put your own logic in around that, for example, to throw some kind of exception.

import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

public class TimeFormatter {

    private NavigableMap<Long,String> timeUnits = new TreeMap<>();

    public TimeFormatter() {
        timeUnits.put(Long.MIN_VALUE, " is not a valid argument");
        timeUnits.put(1L, " milliseconds");
        timeUnits.put(1000L, " seconds");
        timeUnits.put(60 * 1000L, " minutes");
        timeUnits.put(60 * 60 * 1000L, " hours");
        timeUnits.put(24 * 60 * 60 * 1000L, " days");
        timeUnits.put(365 * 24 * 60 * 60 * 1000L, " years");
        timeUnits.put(1000000L * 365 * 24 * 60 * 60 * 1000L, " million years");
        timeUnits.put(1000000000L * 365 * 24 * 60 * 60 * 1000L, " billion years");
    }

    public String format(long milliseconds) {
        Map.Entry<Long,String> unitBelow = timeUnits.floorEntry(milliseconds);
        return milliseconds / unitBelow.getKey() + unitBelow.getValue();
    }
}


Trials, tribulations, and tributaries (Rainfall challenge)

I'm self-reviewing here, because I found some rough spots. Do not let this keep you, dear reader, from writing a review of your own!

For this review I'll leave the overall approach as-is, and just focus on the details of its implementation. I'm nit-picking like crazy, but that's the fun part.

As mentioned in the question, I'm not super happy with the 2-step "initialization" needed to get a useful Cell instance. Mostly because it makes the Cell class tricky to use. Call #drain or #sink without adding any neighbors, and you get useless results. But at least you can add the neighbors later and try again. But call either method with some but not all neighbors added, it'll memoize possibly incorrect result. Adding neighbors after that won't correct the results.

One solution would be to wrap the Cell usage in an "outer" API. For instance a Terrain class or module, with a #basin_sizes(input) (or initializer) method that uses Cell internally to produce the answer. There'd still be a 2-step "initialization", but it'd be hidden from the outside world and (presumably) handled correctly.

Another (partial) solution would be to null the memoized results whenever a new neighbor is added. This way there wouldn't be the same risk of getting stale results, if, say, #drain was called before all the neighbors were added. It wouldn't solve the problem of #sink being memoized elsewhere, though: A cell's drain might change, but if other cells have already memoized a sink that relies on the cell's previous drain, they won't automatically update. Water doesn't flow uphill.

Speaking of memoizing, there's some inefficiency in the way it's used here. For a sink-cell, #drain will of course evaluate to nil. But memoizing a nil value with ||= has no effect: Next time the method's called, it'll evaluate the right-hand expression all over again - and again and again, always producing nil. The point of memoizing should of course be that the right-hand expression isn't run again.

One way to solve this could be to use a 2nd instance variable to track whether the results been calculated yet:

def drain
  return @drain if @drain_found
  @drain_found = true
  @drain = ...
end

But that's not very elegant.

Alternatively, one could initialize the memoization variable to a separate value/type, like false, and check for that:

def drain
  return @drain if @drain != false
  @drain = ...
end

However, all of this is actually academic. Since the method that's actually called when solving is #sink, and memoization works well for #sink (no risk of a nil value). So in the end, the memoization of #drain doesn't actually matter: It's only called once anyway. In fact, #drain might as well be private.

But perhaps a better alternative overall would be to move the "lowest lower cell"-selection from #drain to #add_neighbor:

def add_neighbor(cell)
  reference = drain ? drain.altitude : altitude # get lowest altitude
  @drain = cell if cell.altitude < reference    # update drain if lower
end

Edit: One could cut that down to

@drain = cell if cell.altitude < (drain || self).altitude

but it's probably clearer as-is.

Obviously, add_neighbor might not be the best name for this method anymore. It's more like "set drain to this cell, maybe, if you feel like it"... yeah, I don't know exactly what the name should be. Maybe just #register_neighbor or something.

Anyway, it'd shift the drain identification to be "up front", and the #drain method could be replaced with an attr_reader.

Implementing the above yields a smaller Cell class, which is nice:

class Cell
  attr_reader :altitude, :drain

  def initialize(altitude)
    @altitude = altitude
  end

  def register_neighbor(cell)
    reference = drain ? drain.altitude : altitude
    @drain = cell if cell.altitude < reference
  end

  def sink
    @sink ||= drain ? drain.sink : self
  end
end

There's still the issue of #sink being memoized, so it shouldn't be called before all neighbors have been added/tested. As far as I can tell, this is a "lesser of two evils" question. Having the memoization there short-circuits the pathfinding, so the cell#sink → cell#sink → cell#sink → ... call stack doesn't have to go full-depth every time, which I feel is worth it. Again, the entire thing can be hidden behind a single API method to protect from premature memoization.

But I won't bother with that. The code's not intended for use outside of this script anyway, so for all intents and purposes the script itself is the wrapper.


Python program to know who wins a tic-tac-toe game

To avoid repetitious code, look for commonality. Here, there's a repeated task of checking whether a group of 3 characters are all the same (and not .). This could be done more generally using a set. Sets don't carry duplicates, so if the set of a group has length 1, that means all characters were the same.

The example below shows this idea, by first extracting the different groups and then iterating over them all. This probably means it's less efficient than it could be - it would be faster to create as few groups as possible - but I think the code is somewhat legible at least.

def check_winner(lst):

    # collect "triplets": rows, columns and diagonals
    rows = lst[:]
    cols = list(zip(*lst))
    diag1 = [row[i] for i, row in enumerate(rows)]
    diag2 = [row[2 - i] for i, row in enumerate(rows)]
    triplets = rows + cols + [diag1, diag2]

    # if all characters in a triplet are the same, and that character
    # is not ".", then that character marks the winner
    for triplet in triplets:
        if len(set(triplet)) == 1 and triplet[0] != '.':
            return triplet[0]
    return 'D'

print(check_winner([ "X.O", "XX.", "XOO"]))


Sum of primes up to 2 million using the Sieve of Eratosthenes

Code readability and style -

I believe that good code should have good style and should be more readable and concise.

According to PEP 8 -

  Never use the characters l (lowercase letter el), O (uppercase
  letter oh), or I (uppercase letter eye) as single character variable
  names.

  In some fonts, these characters are indistinguishable from the
  numerals one and zero. When tempted to use l, use L instead.

I ran a PEP 8 checker over your code, and here are the results -

This means that your code uses inconsistent whitespaces. Therefore, your code (in terms of readability and style) could be improved like this (along with other recommendations) -

def prime_sum(n):
    my_list = [0 for i in range(n+1)]

    my_list[0] = 1
    my_list[1] = 1

    for i in range(2, int(n**0.5) + 1):
        if my_list[i] == 0:
            for j in range(i*i, n+1, i):
                    my_list[j] = 1
    s = 0
    for i in range(n):
        if my_list[i] == 0:
            s += i
    print(s)

if __name__ == '__main__':
    prime_sum(2000000)

Also, good use of the if __name__ == __'main__': guard. Most people don't even attempt to use it.

Improvements to your code -

Python provides a set type which is quite efficient at performing both of those operations (although it does chew up a bit more RAM than a simple list). Gladly, it's easy to modify your code to use a set instead of a list. Computation with sets is much faster because of the hash tables (What makes sets faster than lists in python?).

Also, we don't need to keep a running total of the sum of the primes. It's better to do that at the end using Python's built-in sum() function, which operates at C speed, so it's much faster than doing the additions one by one at Python speed.

So your code would then look like this -

def eratosthenes(n):
    # Declare a set - an unordered collection of unique elements
    multiples = set()
    for i in range(2, n+1):
        if i not in multiples:
           yield i
           multiples.update(range(i*i, n+1, i))

if __name__ == '__main__':
    # Now sum it up
    prime_sum = sum(eratosthenes(2000000))
    print(prime_sum)

which uses less space too.

If you're wondering what yield is...

  The yield statement suspends function’s execution and sends a value
  back to the caller, but retains enough state to enable function to resume
  where it is left off. When resumed, the function continues execution
  immediately after the last yield run. This allows its code to produce
  a series of values over time, rather them computing them at once and
  sending them back like a list.

Source - https://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/

And if you are wondering what .update() is...

  The update() adds elements from a set (passed as an argument) to the
  set (calling the update() method).

  The syntax of update() is -

A.update(B)

Source - https://www.geeksforgeeks.org/python-set-update/

Now let's time your code -

# %timeit prime_sum(2000000)
>>> 648 ms ± 19.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

which does look pretty slow.

With the improved code, the time to execute greatly decreases -

# %timeit eratosthenes(2000000)
>>> 264 ns ± 2.73 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Key: ms - milliseconds
     ns - nanoseconds

Hope this helps!


It would be much easier just to let the CSS selector engine select the elements to hide:

var hideDepth = function(root, depth) {
   root.find('ul').show(); // Make sure all sublists are visible
   var selector = Array(depth + 1).join(' > li > ul'); // Repeat string
   root.find(selector).hide();
}

var depth = 2;
var selectedUL = $("#tree");

hideDepth(selectedUL, depth);

NOTE: Add the id tree to the top level ul. Your selector $('ul')selects all lists in the document, not just the top one, so your code was unnecessarily called repeatedly for each sub list.

For the string repeating see: https://stackoverflow.com/questions/1877475/repeat-character-n-times.


Writing an implementation of quicksort is fairly easy. Writing a good implementation that works at least reasonably well with almost any input is much more difficult.

Your uses a choice of pivot element that's pretty well know for bad behavior. By choosing the last element in a range (or the first) you essentially guarantee that it runs in \$O(N^2)\$ if the input is sorted. One typical way of preventing this problem is to use a "median of three" to select the pivot element--that is, look at the first, middle and last elements, and use the median of those three as the pivot.

There's one more minor detail there though: you don't just want to choose the median of those three and use it as your pivot. If those three elements are out of order (with respect to each other) you want to sort them, and write them back to the array in their sorted order. This improves behavior (somewhat) during the recursive calls.

Another subtlety that important to correct behavior (rather than just performance) is to use the correct order for your recursive calls. To assure against stack overflow, you always want to sort the smaller of the two partitions first. In conjunction with tail call elimination (which compilers have practiced for years) this can eliminate the possibility of stack overflow. If you want to be even more certain about it, you can change the final recursive call to iteration, so it's not up to the compiler to eliminate the tail recursion.

C++ adds another interesting twist, at least as soon as you start to deal with sorting collections of arbitrary types of objects (rather than just int). In this case, a user may well have written their own swap function that they expect you to use to swap objects of a particular type. Otherwise, you normally want to use std::swap rather than writing a swap of your own. To select between those correctly, you normally want to put using std::swap at the beginning of your partition function, and then use unqualified calls to swap (e.g., do not explicitly call std::swap). This way if the user has written a swap in the same namespace as the type you're sorting (and named it swap, like they should) your sorting routine will find that via ADL, and use it. Otherwise, it'll find std::swap because of the using std::swap;, and use that. This gives the behavior we want: use their swap routine by preference, but use std::swap if they haven't provided one.

A few other points: of course, the standard library has std::sort built in, which is typically implemented as introsort (which is just a quicksort that keeps track of recursion depth, and switches to a heap sort if quicksort is doing poorly for the input it's been given).

This code doesn't really look/feel much like most people expect C++ to be written. Right now, you're mostly using (and passing) indexes into the array. In C you'd more likely use pointers. In C++, you'd probably want to use iterators instead (though you can pass pointers as iterators). In C++ you'd also normally want something like this to be template, so it can be applied to almost any type of object, not just int. In addition, you'd typically allow the user to pass a comparison function so (for example) if they want to sort Person objects that don't support comparison using <, the user can still sort by passing (for example) a lambda expression saying they want to sort by a person's last name and first name (and default to std::less<T>, so if < is defined, it can be used by default, though the user can still pass a different comparison if they want).


If you break, you need to introduce an additional variable.  In my opinion, it's more clear to return as soon as possible from any function.


Better ways to build a linq specification for querying or is this the only way?

I would definitely write it differently but exact result depends on whether your AndSpecification supports only two parameters or it can accept IEnumerable of attachments.

If it has two parameters and you expect to nest those AndSpecifications if you will have more specs to compose then I would write something like this:

var typeSpecification = string.IsNullOrEmpty(type) ? null : new AttachmentFileTypeSpecification(type);
var statusSpecification = string.IsNullOrEmpty(status) ? null : new AttachmentStatusSpecification(status.AsEnum<AttachmentStatus>());
var specificationsToCompose = new IAttachmentSpecification[] {typeSpecification, statusSpecification};

var composedSpecification = specificationsToCompose
                     .Aggregate((IAttachmentSpecification) null, (accumulator, currentSpec) =>
                         {
                             if (accumulator != null && currentSpec != null) return new AndSpecification<Attachment>(accumulator, currentSpec);
                             return accumulator ?? currentSpec;
                         })
                      ?? new AttachmentSpecification();

...

this.Specification = composedSpecification;


template<typename Key, typename U, std::size_t capacity>
class fixed_size_unordered_map {

The underlying map allows for policy customizations of the allocator, key comparator, and hash.  You may want to provide these customization points to users.

    using iterator = typename std::unordered_map<Key, U>::iterator;
    using size_type = typename std::unordered_map<Key, U>::size_type;
    using value_type = typename std::unordered_map<Key, U>::value_type;

Are these common type definitions intended to be private?

    fixed_size_unordered_map(const fixed_size_unordered_map&) = default;
    fixed_size_unordered_map& operator=(const fixed_size_unordered_map&) = default;
    fixed_size_unordered_map(fixed_size_unordered_map&&) = default;
    fixed_size_unordered_map& operator=(fixed_size_unordered_map&&) = default;

If you explicitly define any of the special member functions for a class, you must define them all.  The following five are considered special member functions. (see Rule of Zero/Three/Five)

Destructor
Copy Constructor
Copy Assignment
Move Constructor
Move Assignment

Either explicitly provide the missing destructor (Rule of Five) or don't explicitly define any of them (Rule of Zero).

    if(iter_queue[queue_idx] != items.end()){
        items.erase(iter_queue[queue_idx]);
    }
    const auto ret = items.insert(v);
    if(ret.second){

Undefined behavior here.  If the iter_queue is full, you erase no matter what happens. If insert succeeds, an iterator overwrites the current invalid iterator in the LRU.  If insertion doesn't succeed, nothing happens to the LRU and the current iterator is just invalid.

Check before erasing.  Erase when inserting.  Determine how you want the LRU to behave on failure to insert.

Consider using a circular buffer or writing your own LRU cache adaptor for some buffer type.  By decoupling the LRU functionality, this object can focus on just adapting its interface to the composed-from objects.  It also removes the need to explicitly define a default constructor (unless you define a conversion ctor).


Converting Array of `UINT8` (`unsigned char`) to Array of `Float32` (`float`) Using AVX2

A straightforward transliterating to AVX2 intrinsics works, but I didn't like what the compilers made of it.

For example, an obvious approach is to load 8 bytes, widen them to 8 ints, etc. And that obvious way to do that, I think, is with _mm_loadl_epi64 to do the loading. Unfortunately, MSVC and even GCC refuse to merge a _mm_loadl_epi64 into the memory operand of _mm256_cvtepu8_epi32, and there is no overload of _mm256_cvtepu8_epi32 with an explicit memory operand.. Using _mm_loadu_si128 to do the loading is fine and does merge, but that merger means that the 16-byte loading intrinsic is used but only 8 bytes of memory are actually loaded. It's strange, but it works, though it may make some people nervous to use this near the end of the data as it looks like it would read past the end.

Anyway, my first concern was the stores. The GCC auto-vectorized version split the 256bit store into two 128bit stores, perhaps to avoid unaligned 256bit stores. But it's not so hard to align the destination, assuming mO is at least 8-aligned, so I'd say that's a better approach. The ICC auto-vectorized version doesn't try to avoid the big potentially-unaligned stores, perhaps it hopes for the best or thinks it shouldn't matter much. It is my understanding though that we should avoid wide unaligned stores (in the sense of the address actually being unaligned) as long as the cost for doing so is reasonable. The ICC versions also avoids small loads, preferring this construct:

vmovdqu ymm3, YMMWORD PTR [r9+rsi] #15.26
vextracti128 xmm7, ymm3, 1 #15.26
vpsrldq xmm4, xmm3, 8 #15.26
vpsrldq xmm8, xmm7, 8 #15.26

I don't like it, this trades 4 loads (in the form of memory operands of vpmovzxbd) for a large load and some shuffle-type operations. That raises the total to 7 shuffle-type operations per iteration, they all need to go to p5 on current Intel µarchs, so that's a likely bottleneck. LLVM-MCA agrees with that and calculates that the loop takes just over 7 cycles per iteration on average, due to p5 contention. Plus, such a larger load increases to ratio of "slow loads" (eg 4K crossings and cache misses) to "fast loads", and makes more work dependent on that slow load, making it less likely that OoOE can hide the slowness.

On the other hand with 4 separate loads, the loop is like this (code below, compiled with ICC):

..B2.8: # Preds ..B2.47 ..B2.6 ..B2.8
  vpmovzxbd ymm2, QWORD PTR [rax+rsi] #34.42
  vpmovzxbd ymm5, QWORD PTR [8+rax+rsi] #36.42
  vpmovzxbd ymm8, QWORD PTR [16+rax+rsi] #38.42
  vpmovzxbd ymm11, QWORD PTR [24+rax+rsi] #40.42
  vcvtdq2ps ymm3, ymm2 #34.23
  vcvtdq2ps ymm6, ymm5 #36.23
  vcvtdq2ps ymm9, ymm8 #38.23
  vcvtdq2ps ymm12, ymm11 #40.23
  vmulps ymm4, ymm0, ymm3 #35.42
  vmulps ymm7, ymm0, ymm6 #37.46
  vmulps ymm10, ymm0, ymm9 #39.47
  vmulps ymm13, ymm0, ymm12 #41.47
  vmovups YMMWORD PTR [rdi+rax*4], ymm4 #35.33
  vmovups YMMWORD PTR [32+rdi+rax*4], ymm7 #37.33
  vmovups YMMWORD PTR [64+rdi+rax*4], ymm10 #39.33
  vmovups YMMWORD PTR [96+rdi+rax*4], ymm13 #41.33
  add rax, 32 #33.43
  cmp rax, rcx #33.39
  jb ..B2.8 # Prob 82% #33.39

Which LLVM-MCA thinks is just under 5 cycles per iteration, which seems good to me. This could be improved slightly by unrolling even more, because the scalar arithmetic does "get in the way" a bit.

By the way I changed some int to size_t to avoid some sign-extension, it wasn't really a big deal though.

void ConvertFromUint8_AVX2(float* mO, unsigned char* mI, size_t numElements, float scalingFctr)
{
    size_t ii;
    __m256 vscalingFctr, tmp;

    vscalingFctr = _mm256_set1_ps(scalingFctr);

    // prologue, do scalar iterations until the output address is 32-aligned
    for (ii = 0; ii < numElements && ((uintptr_t)(mO + ii) & 31); ii++) {
        mO[ii] = (float)(mI[ii]) * scalingFctr;
    }
    // main loop
    if (numElements >= 32) {
        for (; ii < numElements - 31; ii += 32) {
            tmp = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadu_si128((__m128i*)(mI + ii))));
            _mm256_store_ps(mO + ii, _mm256_mul_ps(tmp, vscalingFctr));
            tmp = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadu_si128((__m128i*)(mI + ii + 8))));
            _mm256_store_ps(mO + ii + 8, _mm256_mul_ps(tmp, vscalingFctr));
            tmp = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadu_si128((__m128i*)(mI + ii + 16))));
            _mm256_store_ps(mO + ii + 16, _mm256_mul_ps(tmp, vscalingFctr));
            tmp = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadu_si128((__m128i*)(mI + ii + 24))));
            _mm256_store_ps(mO + ii + 24, _mm256_mul_ps(tmp, vscalingFctr));
        }
    }
    // epilogue
    for (; ii < numElements; ii++) {
        mO[ii] = (float)(mI[ii]) * scalingFctr;
    }
}


How to run canvas animation without effecting other javascript code

One solution to allow multiple functions called when the page loads is to add a callback using EventTarget.addEventListener() for the DOMContentLoaded event.

window.addEventListener('DOMContentLoaded', function() {
    //canvas init
    //..
});

One could also simply use the load event. Many believe that modern browsers typically won't have DOM elements not query-able via JavaScript- especially if the script tag is loaded in the <body> tag instead of the <head> tag, and thus one wouldn't need to wait for the DOMContentLoaded event.

window.addEventListener('DOMContentLoaded', function() {
  //canvas init
  var canvas = document.getElementById("snow");
  var ctx = canvas.getContext("2d");

  //canvas dimensions
  var W = window.innerWidth;
  var H = window.innerHeight;
  canvas.width = W;
  canvas.height = H;

  //snowflake particles
  var mp = 250; //max particles
  var particles = [];
  for (var i = 0; i < mp; i++) {
    particles.push({
      x: Math.random() * W, //x-coordinate
      y: Math.random() * H, //y-coordinate
      r: Math.random() * 4 + 1, //radius
      d: Math.random() * mp //density
    });
  }

  //Lets draw the flakes
  function draw() {
    ctx.clearRect(0, 0, W, H);

    ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
    ctx.beginPath();
    for (var i = 0; i < mp; i++) {
      var p = particles[i];
      ctx.moveTo(p.x, p.y);
      ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true);
    }
    ctx.fill();
    update();
  }

  //Function to move the snowflakes
  //angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
  var angle = 0;

  function update() {
    angle += 0.01;
    for (var i = 0; i < mp; i++) {
      var p = particles[i];
      //Updating X and Y coordinates
      //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
      //Every particle has its own density which can be used to make the downward movement different for each flake
      //Lets make it more random by adding in the radius
      p.y += Math.cos(angle + p.d) + 1 + p.r / 2;
      p.x += Math.sin(angle) * 2;

      //Sending flakes back from the top when it exits
      //Lets make it a bit more organic and let flakes enter from the left and right also.
      if (p.x > W + 5 || p.x < -5 || p.y > H) {
        if (i % 3 > 0) {
          //66.67% of the flakes
          particles[i] = {
            x: Math.random() * W,
            y: -10,
            r: p.r,
            d: p.d
          };
        } else {
          //If the flake is exitting from the right
          if (Math.sin(angle) > 0) {
            //Enter from the left
            particles[i] = {
              x: -5,
              y: Math.random() * H,
              r: p.r,
              d: p.d
            };
          } else {
            //Enter from the right
            particles[i] = {
              x: W + 5,
              y: Math.random() * H,
              r: p.r,
              d: p.d
            };
          }
        }
      }
    }
  }

  //animation loop
  setInterval(draw, 33);
});
window.addEventListener('DOMContentLoaded', function() {
  console.log('another onload callback');
});
body {
  background: tomato;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="snow" style="display:block;position:fixed;z-index:999;pointer-events:none;"></canvas>


Dimension comparisons for calculating image thumbnail size

Trial and Error programming?

My first feeling is that is poorly written code. Why? It is too complex. Calculating the dimensions of a thumbnail should be an easy task, but this code manages to make it into something that has to be studied for an hour before it can be decrypted.

You use !is_negative() but also is_positive(). Naively I would say: "But those are the same!". But, of course, they are not.

I could live with the fact you feel the need to invoke the GMP library, but really? Nobody has images that big, nor do you use it in places where it matters. You don't even use the three values of the outcome of gmp_cmp(), you only use two.

Since you haven't told us, I start by assuming that your function will always be fed by valid numbers. Normal numbers. If this assumption is wrong you can add an is_numeric() error check, or a conversion at the beginning.

Your variables names are poorly chosen. $widthHeightComparison should be something like $imageIsWiderThanHigh or $imageIsLandscape. Same is true for the other variables: $heightCalc doesn't mean anything.

All your function does is calculate a new width and height, based on four parameters: The width and height of the image and the maximum height and width of the thumbnail.

You've decided that there are seven possible ways in which this must be calculated. Let me number them 1 to 7, from top to bottom. To my surprise they are not all different: 1 = 7, 2 = 4 = 5 and 3 = 6. So really there are only three ways in which you perform your caculation. Did you know this? Clearly not.

I think this code was written, not by thinking about the problem, but by random trial and error. You simply gave it some numbers and every time the outcome wasn't what you expected, you added something to correct that, until, after a couple of hours, it passed all the tests. I guess you could say that this code is the result of Test-driven development. Clearly that is not a good way to approach this problem. I prefer it when somebody thinks about the task at hand before writing down code. Afterall, this is not a complex problem.

So here my first stab at this:

function thumbnailDimensions($imageWidth,$imageHeight,$thumbWidth,$thumbHeight)
// resize to thumbnail while maintaining aspect-ratio
{
  // we resize to the thumbnail width and change the height to keep the aspect-ratio
  $imageHeight = round($thumbWidth*$imageHeight/$imageWidth);
  $imageWidth  = $thumbWidth;
  // the image can now be higher than allowed, so we shrink if needed
  if ($imageHeight > $thumbHeight) {
    $imageWidth  = round($thumbHeight*$imageWidth/$imageHeight);
    $imageHeight = $thumbHeight;
  }
  // return array with result
  return array('width' => $imageWidth,'height' => $imageHeight);
}

So that's all that is needed, as far as I can tell. You see, this is not rocket science.

The answer to your question is: No local variables are needed, but if you do use them, give them proper names. Yes, I am in favor of using local variables if it means you don't have to compute something multiple times.


Mongoose query using conditional formatting and regex

First, using new RegExp on user input is a bit like running eval on user input (though not nearly as bad - usually). If it can be avoided, it should be. In this case, if I pass .*? as the partName, the regex will be /^.*?$/i which will match every entry in the database, or I could pass ( which would result in the function throwing an error. This can be mitigated by escaping all special characters, but still isn't a good idea if there is another way to do this. (I haven't used MongoDB, but it appears the $search key might be useful - MongoDB Docs.

If the built in $search parameter doesn't work for you, then the function should escape all special characters in the search string before creating a RegExp with it.

One way to do this is the following:

function createRegex(userInput) {
  return new RegExp(
    // Escape all special characters except *
    "^" + userInput.replace(/([.+?^=!:${}()|\[\]\/\\])/g, "\\$1")
      // Allow the use of * as a wildcard like % in SQL.
      .replace(/\*/g, ".*") + "$",
    'i'
  );
}

['test', '*test*', '*test', 'test*', '[tes{2}t.'].forEach(test => {
  console.log(test, '=>', createRegex(test))
});

While this may be slightly slower than the current function, it is much safer and can greatly simplify the createQuery function. It also allows createQuery to cover the edge case where * appears in the middle of a string.

createQuery can now be implemented in only a few lines.

function createQuery(userInput, dbField) {
  if (userInput === undefined) {
    return;
  }
  // Trim the input before checking as otherwise searching for a
  // single space could cause problems.
  userInput = userInput.trim();
  if (userInput !== "") {
    query[dbField] = createRegex(userInput);
  }
}

Alternatively, this could be shortened (at the cost of some readability) with

function createQuery(userInput, dbField) {
  if (userInput && userInput = userInput.trim()) {
    query[dbField] = createRegex(userInput);
  }
}


A method that shows maps users are a part of

This would potentially be a very expensive way to do this as you have to query the dtabase once for every group the user is in, i.e. an n+1 query. You should be able to do it with a single query by creating a relation:

class User < ApplicationRecord
  belongs_to :usergroup
  has_many   :groups,     through: :usergroup
  has_many   :maps,       through: :groups

then you can just query the map relation.  An alternative would be to use a join. There is more than one way to do this but you could do:

def fetch_maps
  Map.joins(:mapgroups => {:groups => :users} ).where(user: self)
end

Rails doesn't always run the queries the way you expect so I suggest you run your code in the console or watch your log files to make sure that you are only running one query.


You are probably aware of this but representing floating point numbers in JavaScript is difficult to do without rounding errors
Are you sure you the math is correct in the calculations? Specifically, when subtracting angleObstacle from moveAngle, should angleTarget really be added? I attempted to change it such that angleTarget does not get added when that happens. It appears to allow the green circle to avoid colliding with the obstacle circle. I am not sure why the speed changes... perhaps because of the exponential change with the arc tan or other sin functions.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

const targetX = 50;
const targetY = 50;

const obstacleX = 150;
const obstacleY = 50;

let aiX = 250;
let aiY = 51;

function loop() {
    // Distance between the vector points
    const disTargetX = targetX - aiX;
    const disTargetY = targetY - aiY;

    const disObstacleX = obstacleX - aiX;
    const disObstacleY = obstacleY - aiY;

    // Moves to target by default
    const angleTarget = Math.atan2(disTargetY, disTargetX);
    let moveAngle = angleTarget;

    // If near obstacle, adjust course and try to avoid it
    if (Math.sqrt(disObstacleX * disObstacleX + disObstacleY * disObstacleY) < 60) {
        const angleObstacle = Math.atan2(disObstacleY, disObstacleX);
        moveAngle += /*angleTarget -*/angleObstacle;
    }

    // Move the vector to desired location
    aiX += Math.cos(moveAngle);
    aiY += Math.sin(moveAngle);

    //Drawing
    ctx.clearRect(0, 0, 600, 200);

    ctx.beginPath();
    ctx.fillStyle = "teal";
    ctx.arc(aiX, aiY, 10, 0, Math.PI * 2, true);
    ctx.fill();

    ctx.beginPath();
    ctx.fillStyle = "purple";
    ctx.arc(obstacleX, obstacleY, 10, 0, Math.PI * 2, true);
    ctx.fill();

    ctx.rect(targetX - 20, targetY - 20,40,40);
    ctx.stroke();

    if (aiX > 50) {
        requestAnimationFrame(loop);
    }
}

requestAnimationFrame(loop);
<canvas id="canvas" width="600" height="200"></canvas>

Other review points
In the code snippet above, you will notice that let has been replaced with const for many of the declarations of variables that are not re-assigned within the function - e.g. targetX, targetY, obstacleX, obstacleY, disTargetX, disTargetY . This avoids any unintentional re-assignment.
Also, the original code loops forever. I added a condition in the snippet above - i.e. aiX > 50 which needs to be true in order for the function to be called again (via requestAnimationFrame). This avoids unnecessary processing.


How about:

hobbies = "Hobbies: \nsports (basketball, gym), foods (hamburger, steak, pasta), reading, movie, justfortesting((test1, test2), test3)"
print "\n\nBefore: \n\n" + hobbies

counter = 0
hobbies = hobbies.chars.map do |char|
  next "\n" if char == ',' and counter == 0
  counter += 1 if char == '('
  counter -= 1 if char == ')'
  char
end.join
counter = nil

print "\n\nAfter: \n\n"
hobbies.each_line do |line|
  puts line.lstrip
end


All possible combinations of colors for Mastermind

You are looking for all of the variations (with repetitions) of a given list!

variations :: Int -> [a] -> [[a]]
variations n cs
 | n <= 0 = []
 | n == 1 = map pure cs --  map (\c -> [c]) cs
 | otherwise = variations (n-1) cs >>= \ps -> map (:ps) cs

Where the right side of the last line could be any of the following:

variations (n-1) cs >>= flip map cs . flip (:)

concatMap (\ps -> map (:ps) cs) (variations (n-1) cs)

concat . map (\ps -> map (\c -> c:ps) cs) $ variations (n-1) cs

Pick your poison. They are all equivalent. as >>= f is the same as concatMap f as, because for the list monad join is concat, and fmap is map, so bind = (>>=) is join . fmap = concat . map.

Let me demonstrate how variations is evaluated for cs = "12", n=2.

Since variations 1 "12" = ["1", "2"], we know that variations 2 "12" = concat . map (\ps -> map (\c -> c:ps) "12") $ ["1", "2"]  Let's see what each mapping does.

map (\c -> c:ps) "12" simply takes a character c from "12" and appends it to the beginning of ps. But what's ps? Let's look at the other map.

The outer map simply applies the inner function \ps -> map (\c -> c:ps) "12" to each element of ["1","2"].
As we have seen, this inner function simply takes the list cs and maps the element c to c:ps. In this case it turns "1" into ["11","21"], and "2" into ["12","22"].

So all in all we have the following.

variations 2 "12" = concat . map (\ps -> map (\c -> c:ps) "12") $ variations 1 "12"
                  = concat . map (\ps -> map (\c -> c:ps) "12") $ ["1", "2"]
                  = concat [["11","21"],["12","22"]]
                  = ["11","21","12","22"]

Hope this helps.


Project Euler #12 in Swift - Highly divisible triangular number

I would make the required number of divisors (500 + 1) a parameter of the
function, and move the computation of the number of divisors into a separate
function:

func highlyDivisibleTriangularNumber(requiredDivisors : Int) -> Int {

    var triangleNumber = 0
    var number = 0
    var currentNumberOfDivisors : Int

    do {
        number++
        triangleNumber += number
        currentNumberOfDivisors = countDivisors(triangleNumber)
    } while currentNumberOfDivisors < requiredDivisors

    return triangleNumber
}

func euler12() {
    let number = highlyDivisibleTriangularNumber(500 + 1)
    println(number)
}

Counting the number of divisors is done via the prime factorization (which is good). Your prime factorization is done recursively and returns a dictionary
of factor/exponent pairs. I would prefer an iterative algorithm:

func primeFactorization(var n : Int) -> [Int : Int] {
    var factors : [Int : Int] = [:]
    var factor = 2

    while factor * factor <= n {
        if n % factor == 0 {
            var exponent = 0
            do {
                exponent++
                n /= factor
            } while n % factor == 0
            factors[factor] = exponent
        }
        factor = factor == 2 ? 3 : factor + 2
    }
    if n > 1 {
        factors[n] = 1
    }

    return factors
}

I prefer the explicit if n % factor == 0 instead of if n.isMultipleOf(factor)
with a custom extension, but that might be a matter of taste.

This gives only a small performance improvement, but the function does
now return the factorization, so you don't have to pass an inout argument.

Also the result cannot contain the factor 1 (as in your method). So counting the number of divisors would simply be

func countDivisors(num : Int) -> Int {

    var numDivisors = 1
    for (prime, exponent) in primeFactorization(num) {
        numDivisors *= (exponent + 1)
    }
    return numDivisors
}

The variable names (prime, exponent) might be more descriptive
than (index, factor) in your code. As the prime number (the dictionary key)
is not needed in the loop you can also write

for (_, exponent) in primeFactorization(num) {
    numDivisors *= (exponent + 1)
}

or just

for exponent in primeFactorization(num).values {
    numDivisors *= (exponent + 1)
}

But actually it is more efficient to combine the prime factorization and
the computation of the number of divisors into a single method, without
storing the factors and exponents in an intermediate dictionary:

func countDivisors(var n : Int) -> Int {

    var numDivisors = 1
    var factor = 2

    while factor * factor <= n {
        if n % factor == 0 {
            var exponent = 0
            do {
                exponent++
                n /= factor
            } while n % factor == 0
            numDivisors *= exponent + 1
        }
        factor = factor == 2 ? 3 : factor + 2
    }
    if n > 1 {
        numDivisors *= 2
    }

    return numDivisors
}

and this is much faster (0.02 instead of 0.14 seconds).

The most performance improvement can be gained by taking advantage of the
special form n * (n+1)/2 of the triangle numbers, and this are the same
arguments as in

Project Euler Problem 12 - triangle number with 500 divisors

In Swift this would be

func highlyDivisibleTriangularNumber(requiredDivisors : Int) -> Int {

    var n = 1
    while (countDivisors((n+1)/2) * countDivisors(n) < requiredDivisors) {
        n++;
        if (countDivisors(n/2) * countDivisors(n+1) >= requiredDivisors) {
            break;
        }
        n++;
    }
    let triangleNumber = n*(n+1)/2
    return triangleNumber
}

which runs in 0.006 seconds on my computer.


Unfortunately there are several problems with your code. It only reason it works is because you are using parseInt which (as @wOxxOm shows) fulfills the original task requirements and thus ignores your broken attempts at cleaning the string.

!char == " "

This expression always returns true. Like in most programming languages negation (!) have a higher precedence than the comparison ==, so !char is resolved to false (unless char were an empty string, which in this case it never is) and false == " " resolves to true (to be honest I'm not sure why, I'd have to look it up. JavaScript's rules for non-strict comparison (==) are quite complex.)

So it should be char != " " , or even better char !== " ". Always use strict comparison, unless you have a good reason not to.

char.toLowerCase() === char.toUpperCase()

This is a strange attempt to identify digits (and +/-). There are countless other characters that are not filtered by this.

32-bit signed integer range

You are missing the point of this rule. When the system is assumed not to be able to store integers outside the range, then that means a variable can't hold such a large/low number, so a comparison such as output > intMax can never be true, since output can't physically contain a number larger than intMax.

Don't reuse variables

In output = parseInt(output) you change the type and the semantics of the variable output. This is confusing for the reader. And the name output for the original use of collecting the validated string wrong anyway.

Don't leave out semicolons

JavaScript's automatic semicolon insertion is nearly as complex as its non-strict comparison rules. By leaving out the semicolons you make the code more difficult to read because the reader then has an additional thing they need to consider.

Finally

The big problem here is you using parseInt. For one, as mentioned it's hiding the bugs in the code, and more importantly, you are missing the whole point of this exercise, which is to understand how string to number conversion actually works.


Which is the more preferable font size reset?

The answer is neither.  The idea that 1em = 16px is only true in two scenarios:

The browser's default font-size is 16px and the user has not adjusted it
The user has specified that they want a default font-size of 16px because the browser's default was something other than 16px

There is no way to accurately convert between em and px. If you genuinely want a 14px font-size because your chosen font looks best at 14px, then specify that size:

html { /* or body, doesn't matter */
    font: 14px Tahoma, sans-serif;
}

You're still free to use relative font-sizes elsewhere if that's what you desire (I recommend that you do:  you will only have 1 location where you have to adjust your font-size).  Just keep in mind that your specified font may not be available on the user's device and the fallback font might have very different characteristics than you're expecting (eg. the letters might be the same height, but have a different width or vice versa).  You also might make your user upset because text is too small for them to read.

Honestly, the later example is a terrible practice that should have stopped a long time ago.  The idea that scaling everything to 10px makes math easier is a fallacy, especially when you consider that it is never safe to assume that 1em = 16px.

Here's a pretty common scenario showing why this important to understand:

Imagine your typical 2-column blog.  Sidebar on the left, blog content on the right.  How big do you make the sidebar?  You think to yourself, "300px sounds good", so you do the math:  300 / 16 = 18.75 and use 18.75em as your sidebar's width.  Now you want to add an image to your sidebar that's 300px wide.  Does it fit?  How well does it fit?

If the user's font-size is smaller (rare, but it could happen.  I've seen one source claim that iOS browsers have a default of 14px, but couldn't find anything confirming this), then the image overflows out of the sidebar.  If the user's font-size is larger because they have poor vision, then it fits with lots of extra space.  Extra space is usually ok, but you need to make sure you understand that this can happen and that you need to be able to plan for these scenarios.

Related:

http://filamentgroup.com/lab/how_we_learned_to_leave_body_font_size_alone/
http://csswizardry.com/2011/05/font-sizing-with-rem-could-be-avoided/


Triangle-numbers with lots of divisors (Project-Euler Problem 12)

I'm going to focus on the coding style of your question, as there something to be said on that regard. On the subject of improving or alternate solution on how to do the Project Euler #12, see result of search here on Code Review for euler 12 [python].

Use better names for functions! – If you change your function names to sieve_of_eratoshenes and number_of_divisors you can remove the comments , and instead add proper docstrings explaining more on what the functions does or returns.
Use better names for variables – What are the c, d, d1´, andi` variables? They don't convey their meaning, which they really should.
Avoid top level code inbetween functions – Between your functions you suddenly do primes = SE(13000), and then proceed to use this a global within nod(). Both are code smells. You should gather all of your top level code into a main(), pass the primes as a parameter and call main() like in the following:

import itertools

MAX_FACTOR = 13000
MAX_NUMBER = MAX_FACTOR ** 2

def main():
    primes = sieve_of_erasthones(MAX_FACTOR)

    divisor_count = 0

    for i in itertools.count(1):
        if i > MAX_NUMBER:
            raise ValueError("Will fail as we don't have enough primes!")

        if i % 2 == 0:
           even_divisor_count = number_of_divisors(i+1)
        else:
             odd_divisor_count = number_of_divisors((i+1)//2)

        divisor_count = even_divisor_count * odd_divisor_count

        if divisor_count >= 500:
            break

    print(i*(i-1)/2)

if __name__ == '__main__':
    main()

Do note that this code is untested, and I'm mostly unsure on what the i is and whether i > MAX_NUMBER is the correct test
Possibly add an extension of primes table – Like suggested with i > MAX_NUMBER you should add some sort of test to handle the situation when you run out of primes, and possibly build a method to extend the primes further. This could be done tracking current high, and reiterate over primes already found extending beyond the current high to the double of previous high or similar
Loop on the loop counter – As seen in the code above, I've changed your loop into looping on the i instead of resorting to manually updating the i within the while loop. To still maintain the same functionality, I've added the break statemen as a termination clause on the loop instead.
BUG: Your nod() function will return None if n > max(primes) – Given that the highest number of primes is less than n your code will terminate the loop and return None.
Is it correct to do nd *= t? – I haven't tested, and neither fully grasped your nod() function, but shouldn't it add t to the total number of divisors, and not multiply it?

So to summarize, I think you need to work a little on naming your variables and functions, and add a check for when you code will fail to prevent it producing false and erroneous results. And possibly add a method to extend the primes list if going beyond already calculated primes.


Not "stupidly bad", but you're invoking .push() far more times than needed. It's a variadic function, so group the items into single invocations.

Additionally, I'd probably put a toString() method on the BatchInfo.prototype that will give back the string representation of the object.

Then put the objects directly into what was the batchString array. That way the .toString() method will be invoked when you call .join().

I've included additional small changes below as well.

(function () {
    var info = [],
        b = {
            clear: function () {
                info.length = 0; // Clear all references
            },
            get: function () {
                return info;
            },
            add: function (command, url, data) {
                info.push(new BatchInfo(command, url, data));
                return info;
            },
            toString: function () {
                // Put the `BatchInfo` objects directly into the Array.
                // Now we don't need the `for` loop.
                return ['--batchfull',
                        'Content-Type: multipart/mixed; boundary=batchitems']
                           .concat(info).join('\r\n'); // Not needed-- || '';
            }
        };
    function BatchInfo(command, url, data) {
        this.URL = url || '';
        this.Command = command || '';
        this.Data = data || '';
    }
    // Handle the `toString()` representation here
    BatchInfo.prototype.toString = function() {
        var parts = ['', '--batchitems',
                     'Content-Type: application/http',
                     'Content-Transfer-Encoding: binary',
                     '',  this.Command + ' ' + this.URL + ' HTTP/1.1'];

        if (this.Command !== 'DELETE') {
            parts.push('Content-Type: application/json;type=entry');
        }
        parts.push('', this.Data);
        return parts.join('\r\n');
    };
    function BatchCacheRequest(info, description) {
        this.Info = info || '';
        this.Description = description || '';
        this.SubmitDateTime = new Date().toString('yyyy-MM-dd HH:mm');
    }
    window.batch = b;
})();


Getting a value from a database table dynamically

you could do something like that :

public function showForumTopicsByCat($catId)
{
    $topic_model = $this->loadModel('Forum');
    $this->view->forum_topics = $topic_model->getForumTopics($catId);
    $this->view->render('forum/viewTopics');
}

and on view

<?php
if ($this->forum_categories) {
   for($i=o; $i < $numberCat; $i++){
       echo 'Category1';
    }
   } else {
    echo '
There are no categories.
';
}
?>


Minor improvements

I think defining value_counts = AttributeValueCount('type', 'color') would be more user-friendly than having to pass in a list, so you could just define the constructor as

class AttributeValueCount:
    def __init__(self, *keylist):
        self._keylist = keylist
        self._counts = {key: defaultdict(int) for key in keylist}

and remove that need for an iterable. And if a user still has an iterable to pass to the constructor, they can still unpack it:

keys = ['type', 'color']
value_counts = AttributeValueCount(*keys)

I would also use add and update methods as in a dictionary or a set: add is for a single element and update is for several:

    def update(self, iterable):
        for element in iterable:
            self.add(element)

    def add(self, element):
        for key in self._keylist:
            if key in element:
                self._counts[key][element[key]] += 1
            else:
                self._counts[key]['Non existent'] += 1

You can also simplify this add method using dict.get():

    def add(self, element):
        for key in self._keylist:
            category = element.get(key, 'Non existent')
            self._counts[key][category] += 1

Lastly, the __repr__ method is meant to return an "official" representation of the object, something that could potentialy be passed to eval to reconstruct it. I’d rather use __str__ here, or even something completely different, like the summary you’re talking about:

    def summary(self):
        return '\n'.join(
                '-- {} --\n{}'.format(
                    key,
                    '\n'.join(
                        '\t {}: {}'.format(value, count)
                        for value, count in self._counts[key].items()
                    ))
                for key in self._keylist
        )

Note that I used str.join instead of string concatenation as it is usually faster and more memory efficient.

Major improvements

The first thing I would add is the ability to specify the name of the "missing" category. I have a tendency to consider None in such cases, rather than any arbitrary string, but seeing at your data, it seems like None could be a valid entry. So I'd say: let the user decide based on their data.

There is still a question as where to specify this default: in __init__ or at each update/add call? Both might be valid.

An other change I would make is to completely invert the flow of things. Instead of specifying the keys you're interested in beforehand, you just store the data. And you provide methods to retrieve the counts associated to each key latter, this will allow data exploration to be more dynamic. This will give a session like:

>>> counts = AttributeValueCount(data, missing='Non existent')
>>> print(counts['type'])
farm: 2
wild: 1
extinct: 1
>>> print(counts['color'])
red: 1
orange: 1
None: 1
Non existent: 1
>>> print(counts['volume'])
2000: 1
5000: 1
Non existent: 2

Which seems easier than having to recreate an AttributeValueCount('volume') afterwards.

There, also, you have 2 possibilities:

only store values using __init__, add and update and compute the counts later (\$\mathcal{O}(n)\$ at each __getitem__);
compute the counts upfront (\$\mathcal{O}(n\times{}m)\$) but have a constant time __getitem__.

I would go for the second solution as it is interesting how to deal with missing keys when you first encounter a new category:

from collections import Counter

class AttributeValueCount:
    def __init__(self, iterable, *, missing=None):
        self._missing = missing
        self.length = 0
        self._counts = {}
        self.update(iterable)

    def update(self, iterable):
        categories = set(self._counts)
        for length, element in enumerate(iterable, self.length):
            categories.update(element)
            for category in categories:
                try:
                    counter = self._counts[category]
                except KeyError:
                    self._counts[category] = counter = Counter({self._missing: length})
                counter[element.get(category, self._missing)] += 1
        self.length = length + 1

    def add(self, element):
        self.update([element])

    def __getitem__(self, key):
        return self._counts[key]

    def summary(self, key=None):
        if key is None:
            return '\n'.join(self.summary(key) for key in self._counts)

        return '-- {} --\n{}'.format(key, '\n'.join(
                '\t {}: {}'.format(value, count)
                for value, count in self._counts[key].items()
        ))

Usage being:

>>> from count_attributes import AttributeValueCount
>>> data = [
...     {'name': 'apple', 'type': 'farm', 'color': 'red', 'volume': 2000},
...     {'name': 'orange', 'type': 'farm', 'color': 'orange', 'volume': 5000},
...     {'name': 'elderberry', 'type': 'wild', 'color': None},
...     {'name': 'pythonfruit', 'type': 'extinct'}
... ]
>>> c = AttributeValueCount(data, missing='Non existent')
>>> print(c.summary())
-- type --
     Non existent: 0
     farm: 2
     wild: 1
     extinct: 1
-- name --
     Non existent: 0
     apple: 1
     orange: 1
     elderberry: 1
     pythonfruit: 1
-- volume --
     Non existent: 2
     2000: 1
     5000: 1
-- color --
     Non existent: 1
     red: 1
     orange: 1
     None: 1
>>> c['volume']
Counter({'Non existent': 2, 2000: 1, 5000: 1})
>>> c.add({'foo': 'bar'})
>>> print(c.summary())
-- name --
     Non existent: 1
     apple: 1
     orange: 1
     elderberry: 1
     pythonfruit: 1
-- type --
     Non existent: 1
     farm: 2
     wild: 1
     extinct: 1
-- volume --
     Non existent: 3
     2000: 1
     5000: 1
-- color --
     Non existent: 2
     red: 1
     orange: 1
     None: 1
-- foo --
     Non existent: 4
     bar: 1


Custom algorithm for hashing and un-hashing password

First of all, what you have is an encryption function, not a hashing function (encryption can be reversed by knowing the algorithm and optionally a password, hashing is one way).

For passwords, you always* want to hash, not encrypt (because if an attacker gets your source code, they can easily decrypt the passwords).

You are using a substitution cipher, which is also very easy to break. You might want to look into block or stream ciphers, if you want encryption that is more secure.

As to the code you do have:

function names should start with a lower-case character (classes start with an uppercase one).
with the information given above, it's obvious that the function names don't really fit. Also, you don't need filler words such as It in function names. Something like encrypt(plaintext) and decrypt(ciphertext) would be better.
You shouldn't silently ignore errors. I would add an else clause to your if ($find) and throw an exception.
In UnhashIt you check if the string exists, but you don't do it for the more important HashIt function. This means that UnhashIt(HashIt(text)) != text in some cases, which is not good.
For any real-world code, use bcrypt.

* there are exceptions such as kerberos and password managers, but in use cases where you want to authenticate a user by checking a user supplied password against a stored password (ie whenever you do have a user supplied plaintext password to check against), hashing is the correct way, not encryption
(see the comments/chat for an extended discussion)


Return one particular element first, when iterating a lua table

You are performing the check i==0 and i==1 every time after i has incremented beyond those values. You can reduce this check by creating a lookup table.

lookup = {
    [0] = function()
        return priorityKey, t[priorityKey]
    end,
    [1] = function()
        return next(t, nil)
    end
}

The same can be done for you later checking i == priorityKey. I modified the lookup functions instead to deal with that case:

local function pairsWithPriority (t,priorityKey)
    local i, lookup = 0, {
        [0] = function()
            return priorityKey, t[priorityKey], true
        end,
        [1] = function()
            return next( t, nil )
        end,
    }
    local function closure( _, lastReturnedKey )
        local k, v, b
        if i > 1 then
            k, v = next( t, lastReturnedKey )
        else
            k, v, b = lookup[i]()
            if b then i = i + 1 return k, v end
        end
        if k == priorityKey then --the first element is encountered AFTER it has been manually returned, so discard
            k, v = next( t, k )
        end
        i = i + 1
        return k, v
    end
    return closure
end


I don't think there's anything wrong with the should_send_email version of the code. But I can see that in more complex cases there would be a readability benefit in keeping the after-commit logic next to the condition.
There's no documentation. How do I use the AtomicWithContinuation class? What methods does it have? What guarantees does it provide about which callbacks will be called, when, and in what order?
The name could be improved: callbacks are not the same as continuations.
It would make sense for the after_commit and after_rollback methods to take *args and **kwargs to be passed to the callback:

def after_commit(self, cb, *args, **kwargs):
    """Call cb, passing *args and **kwargs, when this transction commits."""
    self._after_commit.append((cb, args, kwargs))

That would allow you to omit the lambda:

a.after_commit(send_email, result)

There's repeated code for calling all the callbacks in a list. This could be made into a function:

def run_callbacks(callbacks):
    """Run the callbacks in the iterable."""
    for cb, args, kwargs in callbacks:
        cb(*args, **kwargs)

You ask, "can I trust my assumptions in __exit__?" Well, there seem to be three assumptions:

If atomic.__exit__ is called with exc_val=None, it commits the transaction.
If atomic.__exit__ is called with any other value of exc_val, it rolls back the transaction.
If atomic.__exit__ raises an exception, then the transaction was rolled back.

Assumptions 1 and 2 are guaranteed by the docstring for the Atomic class, which says:

  __exit__ commits the transaction or releases the savepoint on normal exit, and rolls back the transaction or to the savepoint on exceptions.

It would be worth adding a comment to your __exit__ method quoting or linking to this guarantee.

Assumption 3 is not guaranteed anywhere I can find, and a look at the source for the Atomic.__exit__ method shows that it tries to roll back the transaction, but this might fail, possibly ending up with the connection being closed, or the needs_rollback flag being set.


Prints Books from a HashMap that are complete or incomplete

Prefer interfaces

public void getIncompleteBooks(HashMap<String, Integer> library) {

As a general rule, you should favor interfaces over implementations as types.

public void getIncompleteBooks(Map<String, Integer> library) {

Now you can change to another Map implementation without changing this method at all.

Object fields

And of course, it would be more common to make library an object field.

private Map<String, Integer> library = HashMap<String, Integer>();

Then you wouldn't have to pass it as a parameter to objects of the class.

public void getIncompleteBooks() {

If you don't do that, you should declare the methods static so people don't expect them to use data from the object.

entrySet()

      for (String book : library.keySet()) {
        if (library.get(book) < 100 && library.get(book) > 0) {
          unfinished++;
        }
      }

While it will work, a keySet is the wrong tool here.  Consider

      for (Map.Entry<String, Integer> book : library.entrySet()) {
        if (book.getValue() < 100 && book.getValue() > 0) {
          unfinished++;
        }
      }

Now you aren't doing a hash operation just to iterate over the collection.

Separate logic and display

You mix your data operations with your display operations.  This can be fragile and hard to maintain, as you end up with many similar methods.  Consider how else you could write this.

public static List<Map.Entry<String, Integer>> getIncompleteBooks(Map<String, Integer> library) {
    List<Map.Entry<String, Integer>> results = new ArrayList<>();

    for (Map.Entry<String, Integer> book : library.entrySet()) {
        int percentFinished =  book.getValue();
        if (0 < percentFinished && percentFinished < 100) {
            results.add(book);
        }
    }

    return results;
}

I made this static because it uses none of the object fields of the class, just the parameters.

Adding the percentFinished variable does two things here.  One, it means that we only call the getValue() function once.  The compiler probably does that anyway.  Two, it makes clear what the value actual means.  This is what is called "self-commenting" code.  It replaces a comment that says, // getValue returns the percent of the book that is finished.

I switched to four column indent because that's more common in Java code.

This is what I would expect a getIncompleteBooks method to do.  It just filters out the books that you don't want.  You can then use it in multiple ways.

public static void displayTitles(Collection<Map.Entry<String, Integer>> books) {
    for (Map.Entry<String, Integer> book : books) {
        System.out.println(book.getKey());
    }
}

This is the basic display method.

public static void displayTitlesOfIncompleteBooks(Map<String, Integer> library) {
    if (library.isEmpty()) {
        System.out.println("Please add some books to your library.");
        return;
    }

    List<Map.Entry<String, Integer>> incompleteBooks = getIncompleteBooks(library);

    if (incompleteBooks.isEmpty()) {
        return;
    }

    System.out.println("You have " + incompleteBooks.size() + " unfinished books. They are:");
    displayTitles(incompleteBooks);
}

This should produce the same output as your original method.

Notice that it uses early return on exceptional conditions like an empty library or no unfinished books.  This avoids heavy nesting.

I used isEmpty rather than comparing the size to 0.  Functionally I can't think of a way that this will matter, but I find this version easier to read.

While this is more code for this specific problem, this allows you to solve other problems easily.  For example,

public static void displayTitles(Map<String, Integer> library) {
    displayTitles(library.entrySet());
}

or

public static double calculateFractionIncomplete(Map<String, Integer> library) {
    if (library.isEmpty()) {
        // consider throwing an exception instead
        System.out.println("Please add some books to your library.");
        return 0.0;
    }

    return getIncompleteBooks(library).size() / (double) library.size();
}

I cast the size to double so that Java wouldn't use integer arithmetic and truncate the result.


Ok, for starters, it mentions on the first challenge:

Always operate on raw bytes, never on encoded strings. Only use hex and base64 for pretty-printing.

Since String is actually a list of encoded Chars, it would make more sense to migrate to an implementation that uses ByteString instead. This data structure is suited for handling raw data, like we will be doing here. There is also a very helpful parser library called attoparsec. It is a parser combinator library, similar to parsec, but specialized for ByteString. Using it to parse the input as a ByteString makes the most sense in this situation.

Parsing ByteStrings

A ByteString can be formed from [Word8] using pack, and it can also be broken apart again using unpack. Word8 is just an 8-bit unsigned integer, and interestingly, an 8-bit unsigned integer is also what is needed for holding the value a single hex-digit! This means that we can parse two Word8s from '0' to 'f' and get a single Word8 which holds the encoded number.

import Control.Applicative (liftA2, liftA3, many)
import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString as B
import           Data.ByteString (ByteString, pack, uncons)
import Data.Bits (shift)
import Data.Char (ord)
-- The strict version is suitable here
import Data.IntMap.Strict (IntMap, fromAscList, (!))
import Data.Word8

hexMap :: IntMap Word8
hexMap = fromAscList $ zip (map ord $ ['0'..'9'] ++ ['a'..'f']) [0..]

hex :: Parser Word8
hex = liftA2 mkWord8 hexChar hexChar
  where
    hexChar :: Parser Word8
    hexChar = choice $ map char8 $ ['0'..'9'] ++ ['a'..'f']

    mkWord8 :: Word8 -> Word8 -> Word8
    mkWord8 a b =
          (hexMap ! fromIntegral a) `shift` 4
        + (hexMap ! fromIntegral b)

hexStr :: Parser ByteString
hexStr = fmap pack (many hex)  -- Parser is a Functor

parseHex :: ByteString -> Either String ByteString
parseHex = parseOnly hexStr

Let's take a look at how the hex parser is put together. First, look at the inner functions. mkWord8 takes two Word8 values and looks both of them up in hexMap. Then, it bit shifts the first result by four bits to the left and adds it to the second result. This means that if the first and second arguments to mkWord8 are "f2", then we will have 11110010 stored in the resulting Word8.

hexChar is a Parser that matches a single character in the range of ['0'..'9'] or ['a'..'f']. This works by mapping char8 :: Char -> Parser Word8 over the list of acceptable characters and then calling choice :: [Parser Word8] -> Parser Word8 to indicate that any of the generated parsers will work.

Now, it is easy to understand how hex works. It is a parser that takes two characters and calls mkWord8 on the results, assuming both characters match. To extend hex in order to allow for arbitrary numbers of hex-digits, we just need to utilize many :: Parser Word8 -> Parser [Word8], as in many hex. To actually use hex, we can utilize parseOnly which will run a parser and return either the results or a String containing an error message if it fails.

Converting bytes to Base64

We are halfway to a working solution now that we can parse an incoming hex string into a ByteString. To make it all the way, we need to convert the ByteString into Base64 and print it. This can be done by first converting to something that we are more familiar with, such as decimals, but it may be possible to convert more directly using a little math. Since we know that Base64 uses 6 bits (64 = 2^6) and Word8 uses 8 bits, we can conclude that both formats will line up every 24 bits. When this happens, we can convert 3 bytes into 4 Base64 characters. If there aren't 3 bytes left to use, we will have to utilize as much as we can before giving up.

-- These two functions pull 3 items or 2 items from the front of the ByteString,
-- respectively. (`uncons` pulls one off)

uncons3 :: ByteString -> Maybe ((Word8,Word8,Word8), ByteString)
uncons3 b = do -- We will use the Monad instance of Maybe by using `do`
    (w1,b1) <- uncons b
    (w2,b2) <- uncons b1
    (w3,b3) <- uncons b2
    Just ((w1,w2,w3), b3)

uncons2 :: ByteString -> Maybe ((Word8,Word8), ByteString)
uncons2 b = do
    (w1,b1) <- uncons b
    (w2,b2) <- uncons b1
    Just ((w1,w2), b2)

---

type Base64 = Char -- Might as well use good 'ol Strings again...

toBase64 :: ByteString -> [Base64] -- [Base64] is equivalent to String
toBase64 b =
    case uncons3 b of
        Just ((w1,w2,w3),b') -> from3Bytes w1 w2 w3 ++ toBase64 b' -- loop
        Nothing -> -- Less than 3 bytes left...
            case uncons2 b of
                Just ((w1,w2),b') -> from2Bytes w1 w2
                Nothing -> -- Less than 2 bytes left...
                    case uncons b of
                        Just (w,b') -> from1Byte w
                        Nothing -> [] -- No more data, so end the string

base64Map :: IntMap Base64
base64Map = undefined

-- Convert 3 Word8's to 4 Chars
from3Bytes :: Word8 -> Word8 -> Word8 -> [Base64]
from3Bytes = undefined

-- Convert 2 Word8's to 2 Chars (drop the remainder)
from2Bytes :: Word8 -> Word8 -> [Base64]
from2Bytes = undefined

-- Convert 1 Word8 to 1 Char (drop the remainder)
from1Byte :: Word8 -> [Base64]
from1Byte = undefined

I'll leave it up to you to finish up by filling in the undefined portions. Keep in mind that you can do bitwise manipulations with Data.Bits. Obviously you will need to break up the 8-bit ByteStrings into smaller chunks in order to reassemble them into 6-bit pieces, and have some mapping from these pieces to their Base64 character representation. I left the stub for base64Map as a reminder of one possible solution here.

There's a lot to digest here, but I think this will give you some other strategies to consider. Good luck and happy coding!


Are you inside a loop? Here is a possible way of doing it

def check(td, tt, trigger, key, ticket_changes)
    if td.send(trigger)
      unless tt.changes.key?(key)
        @run = 0
        return true
      end
      unless tt.changes[key][1] == ticket_changes
        @run = 0
        return true
      end
    end
    return false
end

def metacheck(td, tt)
    [[:tt_closed, :status, "Closed"],
     [:tt_assignee, :assigned_to, td.tt_assignee]].each do |k|
        return if check(td, tt, k[0], k[1], k[2])
     end
end

metacheck(trigger_data, trouble_ticket)

I have used an array of triplets to check the conditions.
The check can further be simplified as

def check(td, tt, trigger, key, ticket_changes)
    return false unless td.send(trigger)
    if !tt.changes.key?(key) or (tt.changes[key][1] != ticket_changes)
        @run = 0
        return true
    end
    return false
end

We can join all the conditions together. But I think this captures the original intension best.


Find the area of the bounding box of a robot's moves on a grid

Function signature

It appears you're only reading from directions, so pass that as a pointer to const.

while loop

You initialize c before the while loop and increment it at the end of each iteration.  Writing it as for will convey the intent more clearly.

Chained conditions

Your first if/else if chain is always testing the same variable, so a switch statement seems more appropriate:

    switch (*c) {
    case 'U': ++y; break;
    case 'D': --y; break;
    case 'R': ++x; break;
    case 'L': --x; break;
    }

You might want to add a default case to indicate when malformed input is received.  I can't tell from the context whether it would be appropriate to print something to stderr or to return an error code (perhaps as a negative return value), so I'll leave that to you.

Don't test all bounds each time

We can now observe that we only need to check y against maxy if we've incremented y, so we can move that test into the switch; similarly with the other cases:

int area(char const *directions)
{
    int x=0, y=0,
        minx=0, maxx=0,
        miny=0, maxy=0;
    for (char const *c = directions;  *c;  ++c) {
        switch (*c) {
        case 'U':
            ++y;
            if (y > maxy) maxy = y;
            break;
        case 'D':
            --y;
            if (y < miny) miny = y;
            break;
        case 'R':
            ++x;
            if (x > maxx) maxx = x;
            break;
        case 'L':
            --x;
            if (x < minx) minx = x;
            break;
        }
    }
    return (maxx - minx) * (maxy - miny);
}

You might want to consider using a max() function to re-write ++x; if (x > maxx) maxx = x; as maxx = max(maxx, ++x);, but I can't really say that one is better than the other - too close to call.  Similarly, you might decide that returning an unsigned type is more appropriate, but that really depends on the code you're calling it from.


Sums for list of ranges (CodeFights Basic Skills)

First let's simplify your existing code.

You already use reduce() to add the elements of sumArray, the same
can be done to replace

    var tempSum = 0
    for i in q[0]...q[1] {
        tempSum += nums[i]
    }

by

let tempSum = nums[q[0]...q[1]].reduce(0, +)

Here an "array slice" is created and then reduced. Note that this
does not duplicate the element storage.

Instead of appending a single-element array

   sumArray += [tempSum]

you can append a single element:

sumArray.append(tempSum)

Each element sumArray is the result of applying one query
to the given numbers, this can be simpler done as a map
operation:

let sumArray = queries.map { q in
    nums[q[0]...q[1]].reduce(0, +)
}

I would define the modulus \$ 10^9+7\$ as a constant (interspersed
with _ for better readability):

let modulus = 1_000_000_000 + 7

There is one problem at your

return sum > 0 ? sum % bigNumber : bigNumber + sum

which becomes apparent only with large input: A negative sum must
also be reduced modulo \$ 10^9+7\$, before adding the modulus
to make it non-negative.

Putting it together, your code would look like this:

func sumInRange(nums: [Int], queries: [[Int]]) -> Int {

    let sumArray = queries.map { q in
        nums[q[0]...q[1]].reduce(0, +)
    }

    let sum = sumArray.reduce(0, +)

    let result = sum % modulus
    return result >= 0 ? result : result + modulus
}

which is probably not faster, but simpler and cleaner ("Swiftier") code.

In order to pass the coding challenge in the given time, you need
a different algorithm. The idea is (and to be honest, I did not invent
this myself but found it here):

First create hashes (dictionaries) which associate with every
index the number of queries starting (resp. ending) at this index.
Then traverse the nums array once, keeping track of a
"multiplier" which indicates how often the number at the current index
occurs in the queries, and accumulate the sum.

An implementation in Swift could look like this:

func sumInRange(nums: [Int], queries: [[Int]]) -> Int {
    var startIndices: [Int: Int] = [:]
    var endIndices: [Int: Int] = [:]

    for q in queries {
        startIndices[q[0], default: 0] += 1
        endIndices[q[1], default: 0] += 1
    }

    var multiplier = 0
    var sum = 0
    for (idx, num) in nums.enumerated() {
        multiplier += startIndices[idx] ?? 0
        sum += num * multiplier
        multiplier -= endIndices[idx] ?? 0
    }

    let result = sum % modulus
    return result >= 0 ? result : result + modulus
}

Further remarks:

You probably need to reduce modulo \$ 10^9+7\$ not only the
final sum but also the intermediate results, in order to avoid an
integer overflow.
A Swiftier way to represent pairs is to use tuples instead
of two-element arrays:

func sumInRange(nums: [Int], queries: [(from: Int, to: Int)]) -> Int


Somewhere on "Stack Overflow" was question like your.

Main idea was remove None from form initialization.

if "change_name" in request.POST:
    change_name_form = ChangeNameForm(data=request.POST, instance=request.user)
    if change_name_form.is_valid():
        change_name_form.save()
        name_message = 'Your name has been changed.'
else:
    change_name_form = ChangeNameForm(instance=request.user)

if "change_password" in request.POST:
    change_password_form = PasswordChangeForm(user=request.user)
    if change_password_form.is_valid():
        change_password_form.save()
        password_message = 'Your password has been changed.'
else:
    change_password_form = PasswordChangeForm(user=request.user)

if "change_email" in request.POST:
    change_email_form = ChangeEmailForm(request.POST, instance=request.user)
    if change_email_form.is_valid():
        ...
        email_message = 'Please click the link in your email to confirm changes.'
else:
    change_email_form = ChangeEmailForm(instance=request.user)

This is my solution. I hope it's help you.


Making grandchild of root null , the right way in C++

This is a very C like approach and you are using C++ so take advantage of that fact.

Get rid of the #define and use nullptr keyword instead.
Name member variables something special such as m_ so Node *m_children[4];
Try use C++ data structures instead of arrays and char* so vector<Node*> children.
Make the Node struct into a class and write getters and setters to encapsulate the new vector structure you should use.
Encapsulate the void display(Node *root) function into a class such:

class Tree
{
    Tree(int depth);// create a tree with x depth
    etc...
    void display();
public:
    Node* m_root;
};

You could create some functionality to able to initialise the tree with some custom data structure.
Add the following code in main into the tree class

for (i=0;i<4;i++)
{
    Node *temp=new Node;
    temp->value=values[i];
    root->child[i]=temp;
    for (int j=0;j<4;j++)
    {
        root->child[i]->child[j]=null;
    }
    std::cout<<"Root value "<<root->child[i]->value<<"\n\n ";
}

PS. Sorry if the code doesn't work; I'm at work and have no way to check it!


Delete engine for deeply nested linked structure

To address the locking overhead in the single-threaded case, my first advice is (as with all performance questions) to measure before optimising!  It's likely that the locking overhead is tiny compared to the queue's memory management.
If you really find you need to streamline the locking, then you'll probably want to have two versions of the engine.  The simplest way to do that is probably to add a boolean parameter to the template, and then use if constexpr at the points where the code differs.  Or perhaps make the lock type a template parameter, and supply a no-op lock when creating the single-thread version.


Counting length-2 substrings that are common to two strings at the same offset -- Python

There is no such word as "occurencies".  In any case, all_two_chars_occurencies is a very long name.  I suggest pairwise_chars.  Note that it could also be written in a style similar to the pairwise() recipe in Python's documentation.

In Python, explicit looping is slightly cumbersome.  Fortunately, Python offers many ways to just do what you want as a "one-liner", without looping.  Here's one approach, which uses a generator expression, and this technique to find its length.

def common_two_chars_occurences(a, b):
    """
    Given 2 strings, a and b, return the number of the positions where
    they contain the same length 2 substring.

    >>> common_two_chars_occurences('xxcaazz', 'xxbaaz')
    3
    >>> common_two_chars_occurences('abc', 'abc')
    2
    >>> common_two_chars_occurences('abc', 'axc')
    0
    """
    return sum(1 for pair
                 in zip(pairwise_chars(a), pairwise_chars(b))
                 if pair[0] == pair[1])


Implementing a queue using a circular buffer

Advice 1

QueueOnCirciularBuffer: you misspelled Circular

Advice 2

Wikipedia gives more canonic names for the data structure. Why not choose, say, CircularBuffer?

Advice 3

Instead of having a single index self.index, why not take two: self.head_index is the index in the underlying storage array holding the head element of the buffer; self.tail_index points into the array location at which next element is inserted. If not efficiency, this adds to maintainability in my opinion.

Advice 4

value = self.buffer[(self.index - self.size+self.max_size)%self.max_size]
self.buffer[(self.index-1+self.max_size)%self.max_size]

Adding self.max_size has not effect since you take the modulo of it.

Advice 5

PEP 8 complains about some aspects of your code layout. Consider using a Python IDE (I use PyCharm); it gives you instant feedback if your code does not adhere to rules in PEP 8.

Advice 6

Its funny that your peak_element returns the tail element of the queue; why not rename it to, say, peak_tail. (And possibly provide peak_head.)

Summa summarum

All in all, I had this in mind:

class CircularBuffer:
    def __init__(self, capacity):
        self.buffer = [0] * capacity
        self.size = 0
        self.capacity = capacity
        self.head_index = 0
        self.tail_index = 0

    def push_element(self, value):
        if self.size == self.capacity:
            raise Exception('The circular buffer is full.')
        self.buffer[self.tail_index] = value
        self.tail_index = (self.tail_index + 1) % self.capacity
        self.size += 1

    def pop_element(self):
        if self.size == 0:
            raise Exception('Popping from an empty circular buffer.')
        ret = self.buffer[self.head_index]
        self.head_index = (self.head_index + 1) % self.capacity
        self.size -= 1
        return ret

    def peek_head(self):
        if self.size == 0:
            raise Exception('Peeking into an empty circular buffer.')
        return self.buffer[self.head_index]

Hope that helps.


Determining if current thread is executing

You need to look at how you can make the Execute method both thread-safe and true to the requirements of the method. You say that it only should return true in the case where the delegate is actually called, but you need to make sure that only one thread can call it at a time. That's where lock comes in. You could potentially do something like:

public class SingleCallAction
{
  private readonly object sync = new object();
  private readonly Action action;
  private bool executed;

  public SingleCallAction(Action action)
  {
    if (action == null)
      throw new ArgumentNullException("action");

    this.action = action;
  }

  public bool Execute()
  {
    if (!executed)
    {
      lock(sync)
      {
        if (!executed)
        {
          action();
          executed = true;
          return true;
        }
      }
    }

    return false;
  }
}

Now, what this class provides is a wrapper around an Action delegate. We use Action because it supports both delegate assignment, or lambda assignment.

The Execute method will first check to see if it has previously been executed (if it has, it will jump down to the return false; as its not the thread that has executed the delegate.

If if hasn't executed, it will lock the sync object to prevent any other threads from executing the inner code block. The compiler is generating Monitor.Enter and Monitor.Exit calls here for you, worth a read up!

After the lock, we check whether the executed flag is set again. This allows us to prevent race conditions for competing threads. Don't worry about race conditions when dealing with the executed flag, as variable reads/writes are always atomic operations (mostly).

If we are the first thread to be executing the delegate, we can then execute it action(), set the flag as executed, and return true.

Any subsequent calls will always result in false.

To use in code:

var action = new SingleCallAction(() => Console.WriteLine("Executed"));

var thread1 = new Thread(() => Console.WriteLine(action.Execute()));
var thread2 = new Thread(() => Console.WriteLine(action.Execute()));

thread1.Start();
thread2.Start();

Should result in:

Executed
True
False


Stored procedure where column to ORDER BY depends on input parameters

It looks like your code produces the intended results (I assume you've tested it), but not for the right reasons.

You misunderstood the way CASE ..  WHEN .. THEN .. END is intended to be used. Check out the official documentation. It has examples. There are supposed to be multiple WHEN .. THEN .. between the CASE and the END.

However, since there is just a single WHEN clause in each CASE clauses, if the WHEN clause is not satisfied, then the whole CASE .. END clause evaluates to NULL. ORDER BY NULL has no effect, so it turns out that only the clauses you want to use are being used. Lucky you.

However, it would improve the code to use CASE in the way it was intended. I can't do it all at once but I can refactor the code slightly.

ALTER Procedure [dbo].[WP_GetAllItems]
    @IsActive        bit,
    @OrderMode       bit,
    @OrderBy         varchar(75)
as
Begin
    Select ItemPartNumber, ItemDescription, CreatedDate, InitialPrice from Items where IsActive = @IsActive order by
    IIF( @OrderMode=0,
        CASE
            WHEN @OrderBy='ItemDescription' THEN ItemDescription
            WHEN @OrderBy='ItemPartNumber' THEN ItemPartNumber
            WHEN @OrderBy='CreatedDate' THEN CreatedDate
            WHEN @OrderBy='InitialPrice' THEN InitialPrice
        END, NULL ) ASC,
    IIF( @OrderMode=1,
        CASE
            WHEN @OrderBy='ItemDescription' THEN ItemDescription
            WHEN @OrderBy='ItemPartNumber' THEN ItemPartNumber
            WHEN @OrderBy='CreatedDate' THEN CreatedDate
            WHEN @OrderBy='InitialPrice' THEN InitialPrice
        END, NULL ) DESC
End


Simplification of Python code (HTML extraction)

Try something like this, you can definitely clean up the two list comprehensions you have, but for now this should suffice.

def first():
    with codecs.open("test.html", "a", "utf-8") as output:
        for i in range(1, 10):
            txt = []
            root = lxml.html.parse('http://test'+str(i)+'.xyz'+'?action=source').getroot()
            for empty in root.xpath('//*[self::b or self::i][not(node())]'):
                empty.getparent().remove(empty)

            #tables = root.cssselect('table.main')  <--Dont need this, its is being overwritten
            tables = root.xpath('//table[@class="main" and not(ancestor::table[@class="main"])]')

            txt += ([lxml.html.tostring(t, method="html", encoding="utf-8") for t in tables])
            text = "\n".join(re.sub(r'\[:[\/]?T.*?:\]', '', el) for el in txt)

            output.write(text.decode("utf-8") + "\n\n")