How to combine items in List to make new items efficiently I have a case where I have the name of an object, and a bunch of file names. I need to match the correct file name with the object. The file name can contain numbers and words, separated by either hyphen(-) or underscore(_). I have no control of either file name or object name. For example:

10-11-12_001_002_003_13001_13002_this_is_an_example.svg

The object name in this case is just a string, representing an number

10001

I need to return true or false if the file name is a match for the object name. The different segments of the file name can match on their own, or combined. In the example above, it should be true for the following cases (not every true case, just examples):

10001
10002
10003
11001
11002
11003
12001
12002
12003
13001
13002

And, we should return false for this case (among others):

13003

What I've come up with so far is this:

public bool IsMatch(string filename, string objectname)
{
    var namesegments = GetNameSegments(filename);
    var match = namesegments.Contains(objectname);
    return match;
}

public static List<string> GetNameSegments(string filename)
{
    var segments = filename.Split('_', '-').ToList();

    var newSegments = new List<string>();
    foreach (var segment in segments)
    {
        foreach (var segment2 in segments)
        {
            if (segment == segment2)
                continue;

            var newSegment = segment + segment2;
            newSegments.Add(newSegment);
        }
    }

    return segments.Concat(newSegments).ToList();
}

This does work so far, but is there a better way to do it, perhaps without nesting foreach loops?

The code you have posted looks ok, but could be improved.

Splitting code into methods is a good thing, but in this case it would have been better if you kept it in the IsMatch() method because you could return early. In its current form you are first creating all combinations of the splitted filename and then you check if the returned list contains the objectname.
If a parametername is a compound word you should name the parameter using camelCase casing. This means objectname and filename should be objectName and fileName.
Omitting braces {} although they might be optional can lead to hidden and therefor hard to find bugs. I would like to encourage you to always use them.
Calling ToList() on an array if you don't use any method of List<T> is superflous if the only intend is to iterate over the elements. But as you have a List<T> segments it would be more common to use the AddRange() method instead of Concat().
You should always validate the parameters which are passed to a public method.

I would create a method which returns an IEnumerable<string> which iterates over an string[] if the Length of the arrayelement is equal to a desired length the method yield's the arrayelement otherwise it builds combinations of the current arrayelement with the following arrayelements.

Because this method is returning an IEnumerable<string> which is executed in a deffered and by using the Any() method which returns as soon as the passed condition is true we would also return early.

I have taken the initial method from generate-combination-using-string-array-in-c-sharp and adjusted it to our needs

private static IEnumerable<string> CreateCombinations(string[] array,  int maxLength)
{
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i].Length == maxLength)
        {
            yield return array[i];
        }
        else
        {
            int length = maxLength - array[i].Length;

            foreach (string combination in array.Skip(i).Where(s => s.Length == length))
            {
                yield return string.Concat(array[i], combination);
            }
        }
    }
}

I would then extend the former IsMatch() method to take a char[] array as well. In this way you wouldn't need to touch the method again if e.g the separators should change.

This method would look like so

public static bool IsMatch(string fileName, string objectName, char[] splitChars)
{
    if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); }
    if (objectName== null) { throw new ArgumentNullException(nameof(objectName)); }

    var segments = fileName.Split(splitChars);

    return CreateCombinations(segments, objectName.Length).Any(s => s == objectName);
}

But it would look neater if we make an extension method out of the CreateCombinations method like so

public static IEnumerable<string> CreateCombinations(this string[] array, int maxLength)
{
    if (array == null) { throw new ArgumentNullException(nameof(array)); }
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i].Length == maxLength)
        {
            yield return array[i];

        }
        else
        {
            int length = maxLength - array[i].Length;

            foreach (string combination in array.Skip(i).Where(s => s.Length == length))
            {
                yield return string.Concat(array[i], combination);
            }
        }
    }
}

and the IsMatch() method would look like so

public bool IsMatch(string fileName, string objectName, char[] splitChars)
{
    if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); }
    if (objectName== null) { throw new ArgumentNullException(nameof(objectName)); }

    return fileName.Split(splitChars)
                   .CreateCombinations(objectName.Length)
                   .Any(s=>s==objectName);

}


Callback of setTimeout function when performing synchronous actions Inside a function I'm calling playgame service. Once I've obtained the needed data (gameBeingPlayed), I need to show a 3..2..1 counter and then start a game.

chooseGameService.playGame(gameDefinitionID)
                .then(function () {

                    vm.container.gameBeingPlayed = chooseGameService.gameBeingPlayed;

                    showGame();

                    counter(3);

                });

 function counter(count) {
        vm.container.counterVisible = true;

        var countDownFrom = count;
        var timer = setInterval(function() { handleTimer(count); }, 1000);

        function handleTimer() {
            if(count === 0) {
                clearInterval(timer);
                //
                initGame();
                vm.container.counterVisible = false;
            } else {
                $('#gameCount').text(count);
                count--;
            }
        }
    }

The things that bothers me is that I had to move the next two lines from the service (promise) callback to the counter in order to execute the code synchronously.

initGame();
vm.container.counterVisible = false;

It works, but it seems semantically wrong for me that initGame() and visibility change is inside the counter function instead of inside the callback of the service (which is inside the controller).

Is there any way I could keep these lines inside the .then() of the controller instead of inside the counter function?

I'd make the counter function return a promise. If you understand promises, I think this example will be enough. If not, please ask and I'll clarify.

function counter(count) {
    var deferred = Promise.defer();

    var countDownFrom = count;
    var timer = setInterval(function() { handleTimer(countDownFrom); }, 1000);

    function handleTimer(count) {
        if (count === 0) {
            clearInterval(timer);
            deferred.resolve();
        } else {
            console.log(count);
            countDownFrom--;
        }
    }

    return deferred.promise;
}

Promise.resolve()
    .then(function() {
        console.log('start');
        return counter(3);
    })
    .then(function() {
        console.log('ready');
    });


Checking array for tags I call a service which returns an array of tags. The array may be empty, and if so, it just saves the tag. Otherwise, it checks if the tag is in the array. If so, then the tag is removed, otherwise it's saved.

Can this be optimized for efficiency?

function processTag(total, tag, associatedTicker) {
    var foundFlag = false;

    TagFactory.retrieveTickerTags('onlyTags').then(function(data) {
        console.log('onlyTags data',data);

        // Is there are selected Tags:
        if (data.length > 0) {
            // Search for tag in tagFactory
            for (var i=0; i<data.length; i++) {
                if (data[i].term_id === tag.term_id) {
                    foundFlag = true;
                    break;
                }
            }
            // If found, remove tag:
            if (foundFlag) {
                removeTag(tag, associatedTicker);
            }
            else {
                // Save the tag:
                if (total < 3) {
                    saveTag(tag, associatedTicker);
                }
                // 3 are already selected, display alert:
                else {
                    displayAlert('failure', 'Only 3 tags can be monitored at a time.');
                }
            }
        }
        // Else if there are no selected tags:
        else {
            saveTag(tag, associatedTicker);
        }
    });
}

Here's a rewrite that clarifies and shortens the code.  A few of its advantages:

Removes nested if... else statements
Replaces vague variable name data with something more descriptive.
Names the concepts you are implicitly using in your code (eg, "checkedSave" means "check if it's valid to save the tag, then save it").  We also name the various conditions we are interested in: noSavedTags and tagAlreadyExists.
Avoid unnecessary indendation by not defining our callback saveOrRemoveTag inline.
Avoid verbose, unsightly for loop by using using map and indexOf to check if the tag already exists.
User ternary operator instead of if... else to express simple conditional expressions.

The new code:

function processTag(total, tag, associatedTicker) {

    TagFactory.retrieveTickerTags('onlyTags').then(saveOrRemoveTag);

    function saveOrRemoveTag(savedTags) {

        var noSavedTags = savedTags.length == 0;
        if (noSavedTags) { checkedSave(); return; }

        tagAlreadyExists() ? removeTag(tag, associatedTicker) : checkedSave();

        // the 3 lines above are really the entire function
        // everything below is just helper functions

        function checkedSave() {
            total < 3 ? saveTag(tag, associatedTicker)
                      : displayAlert('failure', 'Only 3 tags can be monitored at a time.');
        }

        function tagAlreadyExists() {
            var existingTermIds = savedTags.map(function(t) { return t.term_id });
            return existingTermIds.indexOf(tag.term_id) > -1;
        }
    }
}


Random distribution in Ruby Below is a Ruby implementation of a random statistical event, based on a hash with the actual observed counts of outcomes.

I'd be interested in feedback in particular on what techniques I might use to avoid a loop-based accumulator in the RandomEvent#predict! method. I'm also very curious as well about any other suggestions on refactoring, patterns and performance that might be applicable here.

The statistics material itself might be somewhat beyond the scope of a review but I'd appreciate any thoughts on appropriate naming and more effective (deterministic) ways to test this.

Spec

include Statistics
describe RandomEvent do
  context 'when an event has only one outcome' do
    it 'always happens' do
      expect(RandomEvent.from_hash(always: 1).predict!).to eq(:always)
    end
  end

  context 'when the event has multiple outcomes' do
    let(:trials) { 10_000 }

    subject(:event) do
      RandomEvent.from_hash(heads: 51, tails: 49)
    end

    it 'should distribute them' do
      coinflips = trials.times.map { event.predict! }

      heads_variance = (coinflips.count(:heads) - trials/2).abs
      tails_variance = (coinflips.count(:tails) - trials/2).abs

      expected_variance = trials/10

      expect(heads_variance).to be < expected_variance
      expect(tails_variance).to be < expected_variance
    end
  end
end

Implementation

class RandomEvent
  def initialize
    @outcome_counts = {}
  end

  def add_outcome(outcome, count:)
    @outcome_counts[outcome] = count
  end

  def normalized_outcome_probabilities
    total_outcome_counts = @outcome_counts.values.reduce(&:+)
    @outcome_counts.inject({}) do |hash,(outcome,count)|
      hash[outcome] = count / total_outcome_counts.to_f
      hash
    end
  end

  def predict!
    acc = 0.0
    roll = rand
    selected_outcome = nil

    normalized_outcome_probabilities.each do |outcome, probability|
      acc += probability
      if acc > roll
        selected_outcome = outcome
        break
      end
    end

    selected_outcome
  end

  def self.from_hash(outcome_counts_hash)
    event = new
    outcome_counts_hash.each do |outcome, count|
      event.add_outcome(outcome, count: count)
    end
    event
  end
end

Unit test

The statistical reasoning in this unit test looks sloppy to me:

context 'when the event has multiple outcomes' do
  let(:trials) { 10_000 }

  subject(:event) do
    RandomEvent.from_hash(heads: 51, tails: 49)
  end

  it 'should distribute them' do
    coinflips = trials.times.map { event.predict! }

    heads_variance = (coinflips.count(:heads) - trials/2).abs
    tails_variance = (coinflips.count(:tails) - trials/2).abs

    expected_variance = trials/10

    expect(heads_variance).to be < expected_variance
    expect(tails_variance).to be < expected_variance
  end
end

It looks like you are flipping a slightly biased coin, but for some reason you expect heads and tails each to be 50%.  Then, for 10000 trials, you're requiring the count of heads and tails to be within the 40%–60% range — a very generous band.

The head count should follow a binomial distribution, namely \$B(n=10000, p=0.51)\$.  Applying Hoeffding's inequality

$$
\mathrm{Pr}(X \le k) \le e^{\frac{-2 (np - k)^2}{n}}
$$

for \$k = 4000\$ gives

$$
\mathrm{Pr}(X \le 4000) \le e^{-242} \approx 8 \times 10^{-106}
$$

The conclusion: for 10 coin flips, sure, the outcome can easily vary by 10%.  For 10000 coin flips, due to the Law of large numbers and the Central Limit Theorem, it basically never happens.  (It would be more likely that your computer is smashed by a meteor during the time it takes to run the test.)

Implementation

The convention is to use the ! suffix on methods that mutate the object.  Your predict! method doesn't really mutate the RandomEvent object, so I wouldn't name it with a !.1

Instead of doing the summation loop in predict!, it might be better to establish the cumulative thresholds in add_outcome, since that happens more rarely.

1 Functional programming purists would note that the method consumes randomness from the pseudorandom number generator when predict! calls rand, and thus it does have a side-effect.  By Ruby standards, though, I wouldn't consider it mutation.  Besides, your add_outcome is much more of a mutation than predict!.


Sum(), ForEach() with Lambda in a hierarchical List Collection I have to list the number of documents related to items in a hierarchical tree.

The specification states:
The tree will only ever be 2 levels deep.
The higher level items will list not only the number of documents in it's folder, but also the total count of documents in the child folders.   They want this total to include the documents in the current folder.

I've developed the solution below, it works, however it just seems complicated, hard to maintain and probably not the most efficient way to do this.  Also, if the tree is ever more than 2 levels deep, this will fail.

class Item
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public int DocumentCount { get; set; }
    public int ChildItemCount { get; set; }
    public int ChildCount { get; set; }
}

static class Program
{
    static void Main()
    {
        var items = new List<Item>
        {
            new Item {Id = 1, ParentId = 0},
            new Item {Id = 2, ParentId = 1},
            new Item {Id = 3, ParentId = 1},
            new Item {Id = 4, ParentId = 2},
            new Item {Id = 5, ParentId = 2},
            new Item {Id = 6, ParentId = 3},
            new Item {Id = 7, ParentId = 3},
            new Item {Id = 8, ParentId = 3}
        };
        // setup
        var rnd = new Random();
        items.ForEach(c => c.DocumentCount = rnd.Next(1, 10));

        // act
        items.ForEach(z => z.ChildCount = items.Count(x => x.ParentId == z.Id));
        items.ForEach(z => z.ChildItemCount = items.Where(x => x.ParentId == z.Id).Sum(y => y.DocumentCount) + z.DocumentCount);
        items.Where(k => k.ParentId == 0).ToList().ForEach(z => z.ChildItemCount = items.Where(x => x.ParentId == z.Id).Sum(y => y.ChildItemCount) + z.DocumentCount);

        // output
        items.ForEach(i => Console.WriteLine("Id: {0}, ParentId: {1}, DocumentCount: {2}, ChildCount: {3}, ChildItemCount: {4}", i.Id, i.ParentId, i.DocumentCount,i.ChildCount, i.ChildItemCount));
        Console.ReadKey();
    }
}

This gives the output below which is technically correct and meets the spec, but I just feel the solution is not the best solution.  Can anyone think of a better way to do this?

Id: 1, ParentId: 0, DocumentCount: 8, ChildCount: 2, ChildItemCount: 46
Id: 2, ParentId: 1, DocumentCount: 7, ChildCount: 2, ChildItemCount: 16
Id: 3, ParentId: 1, DocumentCount: 8, ChildCount: 3, ChildItemCount: 22
Id: 4, ParentId: 2, DocumentCount: 2, ChildCount: 0, ChildItemCount: 2
Id: 5, ParentId: 2, DocumentCount: 7, ChildCount: 0, ChildItemCount: 7
Id: 6, ParentId: 3, DocumentCount: 9, ChildCount: 0, ChildItemCount: 9
Id: 7, ParentId: 3, DocumentCount: 1, ChildCount: 0, ChildItemCount: 1
Id: 8, ParentId: 3, DocumentCount: 4, ChildCount: 0, ChildItemCount: 4

You can create lookup for children. That will involve single enumeration over items collection instead of enumerating all items for each calculation of each item.

I.e. you currently have 2 * N * N iterations for calculating child count and child item count. With lookup you will have N + N + N iterations

var children = items.ToLookup(i => i.ParentId);

foreach(var item in items)
{
    var subitems = children[item.Id];
    item.ChildCount = subitems.Count();
    item.ChildItemCount = subitems.Sum(i => i.DocumentCount) + item.DocumentCount;
}

Explanation: Let's look on this line

items.ForEach(z => z.ChildItemCount =
    items.Where(x => x.ParentId == z.Id).Sum(y => y.DocumentCount) + z.DocumentCount);

Here for each item in items collection you enumerate every item in items collection to get only items which are children of current. That gives you N * N iterations totally. Count is calculated same way.

Now lets look on my code.

var children = items.ToLookup(i => i.ParentId);

Here lookup is created. Internally it looks like enumerating over items and adding them to appropriate groupings of lookup. You can think of lookup as a Dictionary<TKey, List<TValue>>.

Next we do enumerating of all items (that's another N). In body of this loop we get children of item (getting appropriate group by key is pretty fast O(1) operation, comparing to enumerating all items and filtering them). Good news here is behavior of lookup when key not found - it simply returns EmptyEnumerable (i.e. empty array of TValue), so we don't need to check anything - further calculations will work without problems:

foreach(var item in items)
{
    var subitems = children[item.Id];
    // ...
}

Next we do two operations. First is getting count of items in group. Grouping implements ICollection with Count property, and it simply returns count of items in group, without enumerating them:

item.ChildCount = subitems.Count();

Second operation is calculating sum of documents in group. Thus total number of items in all groups will be N then enumerating all groups will take N iterations:

item.ChildItemCount = subitems.Sum(i => i.DocumentCount) + item.DocumentCount;

UPDATE: Thus you want ChildItemCount to contain sum


Pig latin translating program About 2 months ago I started studying python and then 3 days ago sat and began to write a program (found the dumbest & simplest thought I could: a pyglatin translator). I finally got it working 100%. Being a beginner I would love to hear some constructive criticism on my program; I know I have probably written more then was needed on some stuff and taken a long way around on others.
another_word = " "
sentence1 = " "
new_list = []
another = " "

def trans_one_word (i):
    global another_word
    pyg = 'ay'

    original = (i)

    if len(original) > 0 and original.isalpha():
        word = original.lower()
        first = word[0]
        new_word = word + first + pyg
        another_word = new_word[1:len(new_word)]
        return another_word
    else:
        print('empty')

def input_state():

    sentence = input("enter a word to be translated: ")
    list = sentence.split()
    for i in list:
        trans_one_word(i)
        new_list.append(another_word)
    s = " "
    print (s.join( new_list ))

input_state()

another = input("Would you like to enter another sentence to be     translated? \n Y/N")

if (another == 'y') or (another == 'Y'):
    input_state()

All in all I am proud of myself for actually writing it without any help, or all of it except the last "if" statement (I had minor problems with it).

Some comments on your code. Overall you are using a lot of unnecessary variables.

another_word = " "
sentence1 = " "
new_list = []
another = " "

You really don't need these variables declared outside of your functions, they add no value and just pollute the namespace.

def trans_one_word (i):

PEP8 doesn't recommend a  before the args. And you should consider having more meaningful arg names.

    global another_word

Unnecessary global, you are returning this variable from the function so don't need it to be global

    pyg = 'ay'

    original = (i)

Parens are unnecessary and you could just call the arg original as you don't need this assignment.

    if len(original) > 0 and original.isalpha():
        word = original.lower()
        first = word[0]
        new_word = word + first + pyg
        another_word = new_word[1:len(new_word)]

You don't need len(new_word) on a slice an empty slice implies to the end of the word, e.g. new_word[1:]

        first = word[0]
        new_word = word + first + pyg
        another_word = new_word[1:len(new_word)]
        return another_word

This whole block can be simplified to return word[1:] + word[0] + pyg

    else:
        print('empty')

You don't need the else: clause because the previous block returned. You should also return the original word.

def input_state():

    sentence = input("enter a word to be translated: ")

Assume you meant to ask for a words or a sentence given the variable name:

    list = sentence.split()

list is a python type, so shouldn't be used for a variable name.

    for i in list:
        trans_one_word(i)
        new_list.append(another_word)
    s = " "

You should look into list comprehensions and generators as this can be significantly simplified, e.g. print(" ".join(trans_one_word(i) for i in sentence.split()))

    print (s.join( new_list ))

It's probably better to return this result and let the caller print it.

input_state()

another = input("Would you like to enter another sentence to be     translated? \n Y/N")

if (another == 'y') or (another == 'Y'):
    input_state()

This condition can be replaced with if another in 'yY':
You should really put this all into a loop so with an exit clause.

Simplifying the code:

def trans_one_word(word):
    pyg = 'ay'

    if word and word.isalpha():
        word = word.lower()
        return word[1:] + word[0] + pyg
    return word

def input_state():
    sentence = input("enter a sentence to be translated: ")
    return " ".join(trans_one_word(word) for word in sentence.split())

while True:
    print(input_state())
    another = input("Would you like to enter another sentence to be translated?\nY/N")
    if another not in 'yY':
        break


Is this the correct way to implement a HMAC token system? I'm architecting a basic SSO solution to pass a user between two sites.

Site A handles authentication against a user database and then generates links to Site B which pass a HMAC token comprising a nonce and the user's ID. The HMAC is hashed with a shared secret between the two sites.

The following shows the token generation in PHP.

$sso['nonce'] = hash('sha1', rand() );
$sso['sharedKey'] = 'someVerySecureString';
$sso['hmacKey'] = hash_hmac ( 'sha256', $test['sharedKey'] , $test['nonce'] );
$sso['userId'] = '123456';
$sso['hmac'] = hash_hmac ( 'sha256', $test['userId'] , $test['hmacKey'] );
$sso['url'] = '/?id=' . urlencode($test['userId']) . '&nonce=' . urlencode($test['nonce']) . '&hmac=' . urlencode($test['hmac']);

I'm using the nonce to HMAC the key before transmission.

This is the PHP function on Site B to validate the token:

function validateSSOToken($sharedKey='someVerySecureString') {

    $isValid = false;

    if ( isset( $_GET['id'] )
      && isset( $_GET['nonce'] )
      && isset( $_GET['hmac'] )
      && strlen( $_GET['nonce'] ) == 40
      && strlen( $_GET['hmac'] ) == 64) {

        $userId = $_GET['id'];
        $nonce = $_GET['nonce'];
        $hmac = $_GET['hmac'];

        // Sign the key with the nonce to get the tmp key
        $hmacKey = hash_hmac ( 'sha256', $sharedKey, $nonce );

        // rebuild the string to sign
        $localHmac = hash_hmac ( 'sha256', $userId , $hmacKey );

        // Compare against the incoming key
        $isValid = $localHmac == $hmac ? true : false;

    }
    return $isValid;
}

I'm aware of the replay attack vector and will be addressing it in due course.

Could you advise if this is secure? Is there anything else I might look at considering to achieve the same goal?

This looks good.

I do almost exactly the same thing as a password reset mechanism. I am including it here in case it will help you with adding a timer to help prevent replay attacks.

The user receives an email with a link to click to reset their password (the $oldpassword is the nonce because once the password is changed once, it is not valid anymore and the HMAC key is the old password salt (used by the php crypt function)).

$time = time();
$userid = $user->id;
$oldpassword = hash('sha256', $password_info['Password']);
$token = "t={$time}&i={$userid}&o={$oldpassword}";
$verification = hash_hmac('sha256', $token, $password_info['Salt']);

$newpasswordurl = Router::url('user_r')->uri(array(
    't' => $time,
    'i' => $userid,
    'o' => $oldpassword,
    'v' => $verification,
));

The validation is similar.

$userid = $input['i'];
$time = $input['t'];
$expire_time = date_create_from_format('U', $input['t'])->add(date_interval_create_from_date_string(self::$settings['ResetPassword']['LinkValidityTime']));
$oldpassword = $input['o'];
$hash = $input['v'];

$p_info = self::getPasswordParts($OldPassword);

$token = "t=$time&i=$UserID&o=$oldpassword";
$correct_hash = hash_hmac('sha256', $token, $p_info['Salt']);

if ( ($hash != $correct_hash) || ($oldpassword != hash('sha256', $p_info['Password'])) ) {
    throw new ChangePasswordException("That password link is invalid, has expired or has been used.");
}


Simple Haskell Parser I'm very new to haskell (I never used Monads, Functors and other things) and FP in general. I decided to write the simplest parser I possibly can with some expansion possibilities. (I have a general interest in programming languages, so this is why I chose to do this...).
I have a simple parser type:
type Parser a = String -> (Maybe a, String)
-- (Nothing, ErrorMessage)
-- (Just a, Leftovers)

I can parse any character and return an error if there are none:
eatParser :: Parser Char
eatParser []     = (Nothing, "Unexpected EOF")
eatParser (x:xs) = (Just x, xs)

I can parse a specific character:
charParser :: Char -> Parser Char
charParser c s = case eatParser s of
    (Nothing, e) -> (Nothing, e)
    (Just x, xs) | x == c -> (Just x, xs)
    (Just x, _) | x /= c ->
        (Nothing,
        "Expected " ++ [c] ++ ", but got " ++ [x] ++ " instead.")

Also, a specific string:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser u s = case charParser (head u) s of
    (Nothing, e) -> (Nothing, e)
    (Just x, xs) -> case stringParser (tail u) xs of
        (Nothing, e) -> (Nothing, e)
        (Just x', xs') -> (Just $ x : x', xs')

And any word:
varParser :: Parser String
varParser s = case eatParser s of
    (Nothing, _) -> (Just [], [])
    (Just x, xs) | not $ isLetter x -> (Just [], xs)
    (Just x, xs) | isLetter x ->
        case varParser xs of
            (Nothing, e') -> (Nothing, e')
            (Just [], _) -> (Just [x], xs)
            (Just x', xs') ->
                (Just $ x : x', xs')

And finally, the expression parser
data Expr = Open Expr | Value String deriving (Show)
exprParser :: Parser Expr
exprParser s = case charParser '(' s of
    (Nothing, _) -> case varParser s of
        (Nothing, e) -> (Nothing, e)
        (Just x, xs) -> (Just $ Value x, xs)
    (Just _, xs) -> case exprParser xs of
        (Nothing, e)  -> (Nothing, e)
        (Just q, xs') -> case charParser ')' xs' of
            (Nothing, e)   -> (Nothing, e)
            (Just _, xs'') -> (Just $ Open q, xs'')

Here are some examples of what the code does:

*Test2> eatParser "abc"
(Just 'a',"bc")
*Test2> charParser 'a' "abc"
(Just 'a',"bc")
*Test2> charParser 'b' "abc"
(Nothing,"Expected b, but got a instead.")
*Test2> stringParser "abc" "abce"
(Just "abc","e")
*Test2> stringParser "abc" "abc"
(Just "abc","")
*Test2> stringParser "abc" "axbc"
(Nothing,"Expected b, but got x instead.")
*Test2> varParser "abc"
(Just "abc","")
*Test2> varParser "abc2"
(Just "abc","2")
*Test2> varParser "abc abc2"
(Just "abc"," abc2")
*Test2> exprParser "((aa))bc"
(Just (Open (Open (Value "aa"))),"bc")
*Test2> exprParser "((aa)b)bc)"
(Nothing,"Expected ), but got b instead.")

I know that there is a way to simplify all of the
case ... s of (Nothing, e) -> (Nothing, e) (Just x, xs) -> ...
And not use parserSequence...
Can you tell what I can improve? Thanks in advance :D

Short Answer
This looks like a decent attempt.  There are a few minor stylistic issues, but I think the biggest conceptual problem is a bad choice of Parser type.  You should separate ErrorMessage from Leftovers, as these aren't the same sort of thing and so shouldn't share a single field in the algebraic type.  Much clearer is:
type Parser a = String -> Either Error (Maybe a, String)
type Error = String

You've acknowledged that you've never used monads and functors.  Well, there's no time like the present!  Parsers and monads are a match made in heaven.  With the cost of some gnarly monad boilerplate, you can rewrite the bulk of your parsing logic in a much cleaner style, as I show below.  Since you have an interest in programming languages and parsing anyway, I'd suggest reading through some tutorials that show how to write monadic parsers from scratch.  It's a great way to start using monads.  See this article or this blog post for example.  These and other older resources are based on the old version of the Monad class, and you'll get error messages about missing Applicative or Alternative instances.  You can see the notes in the 7.10.x migration guide for how to fix old code so it compiles.
Long Answer
If you want to write a non-monadic parser, this looks like a reasonable first attempt.  A few minor stylistic points.  When writing two guards for the same pattern (or compatible patterns), like here:
case ... of
  (Just x, xs) | x == c -> ...
  (Just x, _)  | x /= c -> ...

it's more usual to chain the guards without repeating the pattern:
case ... of
  (Just x, xs) | x == c -> ...
               | x /= c -> ...

Also, if you have two mutually exclusive guards, it's more usual to use otherwise than write a negated form of the guard.  So, charParser would be written:
charParser :: Char -> Parser Char
charParser c s = case eatParser s of
  (Nothing, e) -> (Nothing, e)
  (Just x, xs) | x == c    -> (Just x, xs)
               | otherwise -> (Nothing, "...")

This has a further advantage that if you turn on the ghc -Wall flag, it'll warn you about case statements and function definitions that don't cover all possible patterns, but mutually exclusive guards will generate false positives unless you use otherwise.  (That is, the compiler isn't willing to assume that it's impossible for both x == c and x /= c to fail.)
Also, this is more personal preference, but I think it makes more sense to make the "success" case more prominent by moving it to the front:
charParser :: Char -> Parser Char
charParser c s = case eatParser s of
  (Just x, xs) | x == c -> (Just x, xs)             -- we succeed
               | otherwise -> (Nothing, "...")      -- or experience various...
  (Nothing, e) -> (Nothing, e)                      -- ...types of failure

It's a big newbie mistake to write functions with lots of head and tail calls.  Pattern matching with x:xs is preferred, since it's not only clearer, but if you turn on -Wall and stamp out any warnings, the pattern matching code is guaranteed not to try to take the head or tail of an empty list.  You've done a good job of using patterns instead of head and tail, but I'd extend this to stringParser, too:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser (u:us) s = case charParser u s of
  (Just x, xs) -> case stringParser us xs of
    (Just x', xs') -> (Just $ x : x', xs')
    (Nothing, e) -> (Nothing, e)
  (Nothing, e) -> (Nothing, e)

The use of x' here is confusing though, since I'd expect it to have the same type as x, but x :: Char and x' :: String have different types.  I guess I'd rename the variables to more consistently identify the "rest" of the stream and differentiate it from what we're trying to parse u:us and what we've actually parsed x:xs:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser (u:us) s = case charParser u s of
    (Just x, rest) -> case stringParser us rest of
        (Just xs, rest') -> (Just (x:xs), rest')
        (Nothing, e) -> (Nothing, e)
    (Nothing, e) -> (Nothing, e)

I think this makes the function a little clearer.  Technically, x:xs isn't needed since it's just a copy of u:us, so you could write:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser (u:us) s = case charParser u s of
  (Just _, rest) -> case stringParser us rest of
    (Just _, rest') -> (Just (u:us), rest')
    (Nothing, e) -> (Nothing, e)
  (Nothing, e) -> (Nothing, e)

Some people think it's important to preserve the value u:us for return with @-syntax:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser uall@(u:us) s = case charParser u s of
  (Just _, rest) -> case stringParser us rest of
    (Just _, rest') -> (Just uall, rest')   -- we return "uall" here
    (Nothing, e) -> (Nothing, e)
  (Nothing, e) -> (Nothing, e)

I don't know if this is clearer, and the @-syntax is pretty repulsive.  I think there's a misguided notion that there's a performance gain here by not re-creating the u:us value right after breaking it apart, but GHC optimizes it and produces equivalent code, so use whichever is clearer.
There seems to be a bug in varParser.  In the case with not (isLetter x), the x token is thrown away, so the following test fails:
> varParser "123"
(Just "","23")

This should either return (Just "", "123") or (Nothing, "expected a letter"), I guess.  You don't notice this bug because the recursive call of varParser compensates for it through an extra case.  If you fix it, then that case becomes redundant and the EOF case can be merged with the not-a-letter case, so you can simplify varParser to something more like:
varParser :: Parser String
varParser s = case eatParser s of
  (Just x, rest) | isLetter x -> case varParser rest of
                     (Just xs, rest') -> (Just (x:xs), rest')
                     (Nothing, e) -> (Nothing, e)
  _ -> (Just [], s)

Technically, the (Nothing, e) case can never be triggered, but you need to keep it in to avoid a -Wall warning.
There are two "big ticket" problems with your code, however.  The first is that your choice of Parser data type is poor:
type Parser a = String -> (Maybe a, String)

In the return type here, you use the first Maybe a component as a flag:  if it's Nothing, the second String component is an error.  If it's Just a, the second String component is the rest of the stream.  However, parse errors and rest-of-streams are not semantically comparable things, and it's pure coincidence that they happen to have the same String type, so they shouldn't be represented by the same field in your algebraic type.  From a practical standpoint, if you decided to refactor your code to parse streams of tokens other than Strings or use a different Error type that includes location information, you'll have to do a lot of unnecessary modification.  You also introduce the potential for dumb programming bugs, where you start parsing error message or printing stream remainders on the console, because they're both String and the bad code will type check.  But these practical concerns are probably not that convincing, and in this simple example probably aren't too serious.  It's really just the theoretical, best-practices issue that this is a bad design when a much more straightforward and idiomatic type is available:
type Parser a = String -> Either String (a, String)

Most Haskell programmers would be confused by your Parser type.  But, every Haskell programmer will understand this new Parser type immediately.  The Either error result convention and the String -> (a, String) pattern, and the combination of the two of them, are hardwired into their brains.  You could make it even more obvious by writing:
type Parser a = String -> Either Error (a, String)
type Error = String

Anyway, the resulting rewritten parsers look about the same, for example:
charParser :: Char -> Parser Char
charParser c s = case eatParser s of
    Right (x, xs) | x == c -> Right (x, xs)
                  | otherwise -> Left $ "Expected " ++ [c] ++ ", but got " ++ [x] ++ " instead."
    Left e -> Left e

but I think this new parser type is just a fundamentally better choice.
The second big ticket problem with your code is, as you've acknowledged in the question, the proliferation of nested cases to handle cascading parse failure.  In many types of code, error handling involves handling exceptional situations, and you can usually get away with no more than a few deeply nested cases where the overall "success path" remains clear.  In parsing, failure of parsers is fundamental to the parsing process, and nearly every parser ends up handling multiple failure modes, often (as in your varParser) in ways that involve converting "failure" into "success" or vice versa.
The best way to fix this is to introduce parser combinators.  The combinators themselves can use ugly nested cases in their implementation, but if the combinators have "meaning", they will result in code that's easier to read where it matters.  For example, you could introduce a combinator like:
combine :: (a -> b -> c) -> Parser a -> Parser b -> Parser c
combine f p q s =  case p s of
  Right (x, s') -> case q s' of
    Right (y, s'') -> Right (f x y, s'')
    Left e -> Left e
  Left e -> Left e

Here combine applies two parsers in sequence and -- if they both succeed -- uses a function to combine their results.  With this combinator, you can rewrite stringParser as:
stringParser :: String -> Parser String
stringParser "" s = Right ("", s)
stringParser (u:us) s = combine (:) (charParser u) (stringParser us) s

A satisfy combinator that applies a parser and ensures the result satifies a condition:
satisfy :: (a -> Bool) -> String -> Parser a -> Parser a
satisfy f unexpected p s = case p s of
  Right (x, rest) | f x -> Right (x, rest)
                  | otherwise -> Left unexpected

let's you rewrite charParser as:
charParser :: Char -> Parser Char
charParser c = satisfy (==c) unexpected eatParser
  where unexpected x = "Expected " ++ [c] ++ ", but got " ++ [x] ++ " instead."

These combinators end up being of limited use because not a lot of thought has gone into them.  For example, if you try to rewrite varParser using them, you might try something like:
varParser :: Parser String
varParser s = combine (:) (satisfy isLetter unexpected eatParser) varParser s
  where unexpected x = "Expected a letter, but got " ++ [x] ++ " instead."

but this won't work because the first non-letter character throws an error instead of ending the variable name.
This is why it's worth learning how to use monads for parsers.  A monad is a good fit for the problem of combining parsers together, and it provides a whole host of pre-written combinators that work with any monadic parser.  The combinators have been thoughtfully designed, and you rarely find yourself in the situation where you need to write a combinator from scratch, because you can almost always find one that does what you want.
Anyway, my rewrite of your parser without any combinators would look like this.  It uses the Either-based parser type, reorders the nested cases to put "success" first, and cleans up some variable names and redundant cases:
{-# OPTIONS_GHC -Wall #-}

module MonadlessParser where

import Data.Char

type Parser a = String -> Either String (a, String)

eatParser :: Parser Char
eatParser []     = Left "Unexpected EOF"
eatParser (x:rest) = Right (x, rest)

charParser :: Char -> Parser Char
charParser c s = case eatParser s of
  Right (x, rest) | x == c -> Right (x, rest)
                  | otherwise -> Left $ "Expected " ++ [c] ++
                                 ", but got " ++ [x] ++ " instead."
  Left e -> Left e

stringParser :: String -> Parser String
stringParser [] s = Right ("", s)
stringParser (u:us) s = case charParser u s of
  Right (_, rest) -> case stringParser us rest of
    Right (_, rest') -> Right (u:us, rest')
    Left e -> Left e
  Left e -> Left e

varParser :: Parser String
varParser s = case eatParser s of
  Right (x, rest)
    | isLetter x -> case varParser rest of
                      Right (xs, rest') -> Right (x:xs, rest')
                      Left e -> Left e
  _ -> Right ([], s)

data Expr = Open Expr | Value String deriving (Show, Eq)
exprParser :: Parser Expr
exprParser s = case charParser '(' s of
    Right (_, rest) -> case exprParser rest of
        Right (expr, rest') -> case charParser ')' rest' of
            Right (_, rest'') -> Right (Open expr, rest'')
            Left e -> Left e
        Left e -> Left e
    Left _ -> case varParser s of
        Right (x, rest) -> Right (Value x, rest)
        Left e -> Left e

main :: IO ()
main = do
  print $ eatParser "abc" == Right ('a',"bc")
  print $ charParser 'a' "abc" == Right ('a',"bc")
  print $ charParser 'b' "abc" == Left "Expected b, but got a instead."
  print $ stringParser "abc" "abce" == Right ("abc","e")
  print $ stringParser "abc" "abc" == Right ("abc","")
  print $ stringParser "abc" "axbc" == Left "Expected b, but got x instead."
  print $ varParser "abc" == Right ("abc","")
  print $ varParser "abc2" == Right ("abc","2")
  print $ varParser "abc abc2" == Right ("abc"," abc2")
  print $ exprParser "((aa))bc" == Right (Open (Open (Value "aa")),"bc")
  print $ exprParser "((aa)b)bc)" == Left "Expected ), but got b instead."

Writing a monadic version requires two difficult steps.  First, you have to make your Parser a newtype and write Monad and related instance for it.  This looks like black magic, but you eventually figure out how to do it reliably.  Second, you need to learn about all the applicative and monadic combinators and how to use them.
Once you've done that, the work you put in really pays off.  Here's a full monadic version of your parser with comments that try to explain what's going on.  Setting aside the ugly monadic instances, most of the parsers themselves are straightforward to write and understand.
{-# LANGUAGE DeriveFunctor #-}
{-# OPTIONS_GHC -Wall #-}

module MonadParser where

-- a bunch of combinators
import Control.Applicative
import Control.Applicative.Combinators
import Control.Monad

-- just for `isLetter`
import Data.Char

-- the hardest part, by far, is writing these instances
newtype Parser a = Parser { runParser :: String -> Either String (a, String) }
  deriving (Functor)
instance Applicative Parser where
  pure x = Parser $ \str -> Right (x, str)
  (<*>) = ap
instance Monad Parser where
  p >>= f = Parser $ \str -> case runParser p str of
      Right (x, rest) -> case runParser (f x) rest of
        Right (y, rest') -> Right (y, rest')
        Left e -> Left e
      Left e -> Left e
instance MonadFail Parser where
  fail err = Parser $ \_ -> Left err
instance Alternative Parser where
  empty = fail "<empty>"
  p <|> q = Parser $ \str -> case runParser p str of
    Left _ -> runParser q str
    result -> result
instance MonadPlus Parser

-- we need to rewrite `eatParser` to use a `Parser` newtype
eatParser :: Parser Char
eatParser = Parser go
  where go (x:rest) = Right (x, rest)
        go []       = Left "unexpected EOF"

-- a "satisfy" combinator is helpful; we have pre-written combinators for
-- almost everything else
satisfy :: (a -> Bool) -> Parser a -> Parser a
satisfy f p = do
  x <- p
  guard (f x)
  return x

-- now the hard word pays off...

-- "satisfy" lets us easily write `charParser`
charParser :: Char -> Parser Char
charParser c = satisfy (==c) eatParser

-- `mapM` runs `charParser` for each input character and puts the result
-- together into a list of characters, namely the desired `String`
stringParser :: String -> Parser String
stringParser = mapM charParser

-- this parses a single `letter` using `Data.Char.isLetter`
letterParser :: Parser Char
letterParser = satisfy isLetter eatParser

-- `some` parses one or more of the given parser into a list (in this case,
-- a list of characters, so a `String`)
varParser :: Parser String
varParser = some letterParser  -- non-empty variable name

-- the `between` combinator runs a parser between two other parsers; here
-- `parens p` will run parser `p` between parentheses
parens :: Parser a -> Parser a
parens = between (charParser '(') (charParser ')')

-- Here `<$>` just attaches the desired constructor to the return value
-- from the parsers.  The alternation operator `<|>` tries the first parser
-- and, if it fails, tries the second before giving up.
data Expr = Open Expr | Value String deriving (Show, Eq)
exprParser :: Parser Expr
exprParser = Open <$> parens exprParser
         <|> Value <$> varParser

-- All the tests still pass
main :: IO ()
main = do
  print $ runParser eatParser "abc" == Right ('a',"bc")
  print $ runParser (charParser 'a') "abc" == Right ('a',"bc")
  print $ runParser (charParser 'b') "abc" == Left "<empty>"
  print $ runParser (stringParser "abc") "abce" == Right ("abc","e")
  print $ runParser (stringParser "abc") "abc" == Right ("abc","")
  print $ runParser (stringParser "abc") "axbc" == Left "<empty>"
  print $ runParser varParser "abc" == Right ("abc","")
  print $ runParser varParser "abc2" == Right ("abc","2")
  print $ runParser varParser "abc abc2" == Right ("abc"," abc2")
  print $ runParser exprParser "((aa))bc" == Right (Open (Open (Value "aa")),"bc")
  print $ runParser exprParser "((aa)b)bc)" == Left "<empty>"

I hope that example whets your appetite for trying out monadic parsing.


Finding a way to obtain some volume of water using a large and small bucket I have a set of if/else statements that trigger certain actions. As a first step, I was thinking about moving the logic in each if statement to be its own function, but are there any recommendations on what design patterns can help clean this code up?

I guess I am trying to see if there is a cleaner way to determine what the next action/command should be based on a set of criteria. I see people recommend the Command pattern, but how does one abstract the logic in the if-statement to begin with?

function WaterRetriever(largeBucketSize, smallBucketSize, waterSize) {
    var buckets = {};

    if (waterSize > largeBucketSize) {
        throw new Error("The buckets are not large enough.");
    }

    buckets.firstContainer = new Bucket(largeBucketSize);
    buckets.secondContainer = new Bucket(smallBucketSize);

    this.getWaterFromLake = function () {
        var maxSteps = 25,
            step = 1;

        buckets.firstContainer.fill();

        while (step <= maxSteps && buckets.firstContainer.getCurrentAmount() !== waterSize) {
            if (buckets.firstContainer.isFull() && buckets.secondContainer.isEmpty()) {
                buckets.firstContainer.transferTo(buckets.secondContainer);

            } else if (buckets.secondContainer.isFull() && buckets.firstContainer.hasCapacityAvailable()) {
                buckets.secondContainer.empty();
                buckets.firstContainer.transferTo(buckets.secondContainer);
            } else if (buckets.firstContainer.isEmpty() && buckets.secondContainer.hasCapacityAvailable()) {
                buckets.firstContainer.fill();
            } else if (buckets.firstContainer.isFull() && buckets.secondContainer.hasCapacityAvailable()) {
                buckets.firstContainer.transferTo(buckets.secondContainer);
            }
            console.log(buckets.firstContainer.getCurrentAmount() + ", " + buckets.secondContainer.getCurrentAmount());
            step = step + 1;
        }

        if (step > maxSteps) {
            console.log("could not find a solution within the steps limit...");
        }
    };
}

I found your conditions to be a little confusing. It was hard for me to understand the rules of what is going on by just a quick glance. In this simple case, you don't necessarily need to create more abstraction, just be more clear about presenting the rules.

One way to make your code more readable is to try and avoid an if/else maze if a series of ifs could suffice instead. There's a certain amount of personal preference to that, however, when there are many if/else's, your brain has to stack up and keep track of all the previous conditions. It's better to check a condition, then handle it immediately and return to a higher scope instead of nesting further. By not nesting further, you can "forget" about it and simply move on to the next condition.

A trivial example example:

function describeHeight(person) {
    var height = person.height;
    if (height < 4) {
        console.log('short');
    }
    else if (height >= 4 && height < 6) {
        console.log('average');
    }
    else if (height >= 6 && height < 8) {
        console.log('tall');
    }
    else {
        console.log('giant!!!');
    }
}

Versus:

function describeHeight(person) {
    var height = person.height;
    if (height >= 8) {
        console.log('giant!!!');
        return;
    }
    if (height >= 6) {
        console.log('tall');
        return;
    }
    if (height >= 4) {
        console.log('average');
        return;
    }
    console.log('short');
}

Not the best example, perhaps. But I feel like the second version is easier to read. See how the first example has more nesting, and the second has less?

In your example, I would try to simplify the rules. The logic may not be correct here, because I don't exactly understand your rules, but something like this may be easier to read:

while (step++ <= maxSteps) {
    // Check if container has the appropriate amount of water.
    if (buckets.firstContainer.getCurrentAmount() === waterSize) {
        break;
    }

    // If first container is empty, then fill it.
    if (buckets.firstContainer.isEmpty()) {
        buckets.firstContainer.fill();
        continue;
    }

    // If first container is full, fill up the second container if there's room.
    if (buckets.firstContainer.isFull() && buckets.secondContainer.hasCapacityAvailable()) {
        buckets.firstContainer.transferTo(buckets.secondContainer);
        continue;
    }

    // If second container is full, dump it out, and try to fill up the first container if there's room.
    if (buckets.secondContainer.isFull() && buckets.firstContainer.hasCapacityAvailable()) {
        buckets.secondContainer.empty();
        buckets.firstContainer.transferTo(buckets.secondContainer);
        continue;
    }
}


Import XML files to MongoDb with Nodejs Here is my code which will read XML files and import the data to MongoDb. Do you have any comments on my code?
const fs = require('fs');
const xml2js = require('xml2js');
const log = console.log;
const path = require( "path" );

const folderPath = 'D:/Data';
const folder = folderPath;

fs.readdirSync(folder).forEach(file => {

    const extname = path.extname(file);
    const filename = path.basename(file, extname);
    const absolutePath = path.resolve(folder, file);

    const parser = new xml2js.Parser({
        mergeAttrs: true,
        explicitArray: false
    });

    fs.readFile(absolutePath, (err, data) => {

        parser.parseString(data, (err, result) => {

            var MongoClient = require('mongodb').MongoClient;
            var url = "mongodb://localhost:27017/";

            MongoClient.connect(url, function (err, db) {
                if (err) throw err;

                var dbo = db.db("myDb");

                dbo.collection("entity").insertMany(result, function (err, res) {
                    if (err) throw err;

                    db.close();
                });
            });
        });
    });

});

I tested that it works for few files but for hundreds of files, it can throw an error.

Variable declaration keywords
One thing I notice is that the var keyword is used in some functions while others use const. The variables dbo, MongoClient and url are never reassigned so const can be used for those. Using const when re-assignment isn't needed is a good habit because it can help avoid accidental re-assignment and other bugs. Many users also believe var should not be used with ES6 code - refer to the ES lint rule no-var.
nested callbacks
The code is bordering on callback hell. I'd suggest moving anonymous functions out to being named functions. This will also help with automated testing. Let's look at the inner most function:
const insertionCallback = (db, err, res) {
    if (err) throw err;

    db.close();
};

It needs a reference to db. That could be made a parameter:
function (db, err, res) {

Then when making a reference to that function, make a partially applied function with db as the first argument:
dbo.collection("entity").insertMany(result, insertionCallback.bind(null, db))

Or instead of accepting db as a parameter, set the context to it:
dbo.collection("entity").insertMany(result, insertionCallback.bind(db))

after doing that this could be used instead of db within that insertionCallback function.
Then continue pulling out those nested functions - e.g. :
const insertResult = (result, err, db) => {
    if (err) throw err;

    const dbo = db.db("myDb");

    dbo.collection("entity").insertMany(result, insertionCallback.bind(null, db));
};

Then that function can be used in its outer function:
const handleParsedStr = (err, result) => {

    const MongoClient = require('mongodb').MongoClient;
    const url = "mongodb://localhost:27017/";

    MongoClient.connect(url, insertResult.bind(null, result));
});

And that functions can be used as the callback to parser.parseString():
parser.parseString(data, handleParsedStr);

error handling
Some of the callback functions check error arguments like err and conditionally handle such cases, but others don't- e.g. the callback to parser.parseString(). It is advisable to handle such errors, and would also make the code more consistent.
parser declared within forEach callback function
The variable parser is declared within the callback function to the .forEach() method. This means the parser is created once for each file in the directory. If possible, consider declaring it outside the loop to reduce resource requirements.


Hide and show columns in an HTML table Codepen Link

I've tried to Google, but there's no library that has an API to toggle table columns when clicked elsewhere on the page, so I've decided to do this:

function deleteColumnOnClick() {

    $('.hide div').click(function() {
        var index = $(this).index();
        $('table thead th').eq(index).toggleClass('hidden');
        var hidden = $('table thead th.hidden')
        $.each(hidden, function() {
            var idx = $(this).index();
            $.each($('table tbody tr'), function() {
                $(this).find('td').eq(idx).hide();
            });
        });

        var visible = $('table thead th:not(.hidden)');
        $.each(visible, function() {
            var idx = $(this).index();
            $.each($('table tbody tr'), function() {
                $(this).find('td').eq(idx).show();
            });
        });
    });
}

deleteColumnOnClick();

Is this an awful solution? If yes, how do I refactor it?

Right now, the relationship between the hide/show "buttons" and the columns is pretty fragile. You're dependent on the buttons being in the same exact order as the columns. If you add or remove a button, the indices stop making sense; you can't rely on the 3rd button always being linked to the 3rd column and vice versa.

I'd suggest giving the buttons (or whatever element you use to hide/show columns) a data-column attribute or something similar to make it explicit that this button controls that column. Similarly, the th cells can carry a data-column attribute or simply an ID to identify them.

For instance:

<button type="button" data-column="#column-abc">Hide/show</button>

      A column
      Another column
      Yet another column

  ...

Now it's explicit that the button will hide column #column-abc. And it'll simplify the code too, since relationships between things are no longer just assumed or implied.

Secondly, you're (in a sense) trying to both hide and show the column, and just seeing what works. It'd be simpler to just do a hasClass("hidden") check. There are also some jQuery selector magic you can use.

Something like this, for instance:

// global click handler for any element with a "data-column" attribute
$("[data-column]").on("click", function () {
  var button = $(this),                   // the element that was clicked
      header = $(button.data("column")),  // the cell referenced by the button
      table = header.closest("table"),    // the table in which the cell resides
      index = header.index() + 1,         // convert to CSS's 1-based indexing
      selector = "tbody tr td:nth-child(" + index + ")",  // selector for all body cells in the column
      column = table.find(selector).add(header); // all cells in the column

  // toggle the "hidden" class on all the column cells
  column.toggleClass("hidden");
});

Here's a demo


In matrix of sub-matrices, select diagonal indices of off-diagonal submatrices Let's say I have a square matrix of size (n*m) x (n*m) that is composed of n x n sub-matrices, with each submatrix being a square of size m x m.

I want to select the diagonal indices of the off-diagonal submatrices. This is the code that I have so far, but I would like to do this without the calls to itertools.permutations if possible.

n_submatrix = 3
submatrix_size = 2
my_matrix = np.zeros([n_submatrix * submatrix_size,
                      n_submatrix * submatrix_size])

for submatrix_index in itertools.permutations(range(n_submatrix),2):
    my_slice0 = slice(submatrix_index[0]*submatrix_size, (submatrix_index[0]+1)*submatrix_size)
    my_slice1 = slice(submatrix_index[1]*submatrix_size, (submatrix_index[1]+1)*submatrix_size)
    np.fill_diagonal(my_matrix[my_slice0,my_slice1],1)

my_matrix

#array([[ 0.,  0.,  1.,  0.,  1.,  0.],
#       [ 0.,  0.,  0.,  1.,  0.,  1.],
#       [ 1.,  0.,  0.,  0.,  1.,  0.],
#       [ 0.,  1.,  0.,  0.,  0.,  1.],
#       [ 1.,  0.,  1.,  0.,  0.,  0.],
#       [ 0.,  1.,  0.,  1.,  0.,  0.]])

I'm sure there are other ways, but in the meantime, how about this:

my_matrix = np.tile(np.eye(submatrix_size), (n_submatrix, n_submatrix))
np.fill_diagonal(my_matrix, 0)

Then again, the concatenation of matrixes might not be particularly
efficient, so instead I'd rather compute the target indexes directly,
fill them, and possibly clear out the diagonal again (all destructive on
a previously allocated matrix):

cells = n_submatrix * submatrix_size
my_matrix = np.zeros((cells, cells))

for x in range(n_submatrix):
    for y in range(submatrix_size):
        r = range(y, n_submatrix * submatrix_size, submatrix_size)
        my_matrix[x * submatrix_size + y, r] = 1

np.fill_diagonal(my_matrix, 0)

That is still easily explained:  we step first by number of submatrixes
(because that's where the pattern repeats), then for each row we set all
indexes in that row at once, offset by the current step in the
submatrix.

Again, that seems less efficient than calculating indexes at once.  I
ended up with the following:

cells = n_submatrix * submatrix_size
my_matrix = np.zeros((cells, cells))

for y in range(submatrix_size):
    r = range(y, n_submatrix * submatrix_size, submatrix_size)
    my_matrix[np.ix_(r, r)] = 1

np.fill_diagonal(my_matrix, 0)

To be fair, the documentation for numpy.ix_ and
indexing
isn't particularly intuitive, but basically I was looking for a way to
compress the notion of "for each of these rows, select all the indexes
in that row" and then setting them all at once.  Now there is only one
loop for each row in the submatrix and I'm out of ideas.

There might be a clever formula to generate all of the indexes in one go
(by calculating them modulo some number) for all the diagonals though.

Btw. for your code I'd suggest extracting expressions as variables (like
cells above) and possibly a bit more succinct names, but that's just
me.


Given a random section of text delimited by line breaks, get the first paragraph Requirements:

  Given a long section of text, where the only indication that a paragraph has ended is a shorter line, make a guess about the first paragraph. The lines are hardwrapped, and the wrapping is consistent for the entire text.

The code below assumes that a paragraph ends with a line that is shorter than the average of all of the other lines. It also checks to see whether the line is shorter merely because of word wrapping by looking at the word in the next line and seeing whether that would have made the line extend beyond the "maximum" width for the paragraph.

def get_first_paragraph(source_text):
    lines = source_text.splitlines()
    lens = [len(line) for line in lines]
    avglen = sum(lens)/len(lens)
    maxlen = max(lens)
    newlines = []
    for line_idx, line in enumerate(lines):
        newlines.append(line)
        try:
            word_in_next_line = lines[line_idx+1].split()[0]
        except IndexError:
            break # we've reached the last line
        if len(line) < avglen and len(line) + 1 + len(word_in_next_line) < maxlen: # 1 is for space between words
            break
    return '\n'.join(newlines)

Sample #1

Input:

This is a sample paragaraph. It goes on and on for several sentences.
Many OF These Remarkable Sentences are Considerable in Length.
It has a variety of words with different lengths, and there is not a
consistent line length, although it appears to hover
supercalifragilisticexpialidociously around the 70 character mark.
Ideally the code should recognize that one line is much shorter than
the rest, and is shorter not because of a much longer word following
it which has wrapped the line, but because we have reached the end of
a paragraph.
This is the next paragraph, and continues onwards for
more and more sentences.

Output:

This is a sample paragaraph. It goes on and on for several sentences.
Many OF These Remarkable Sentences are Considerable in Length.
It has a variety of words with different lengths, and there is not a
consistent line length, although it appears to hover
supercalifragilisticexpialidociously around the 70 character mark.
Ideally the code should recognize that one line is much shorter than
the rest, and is shorter not because of a much longer word following
it which has wrapped the line, but because we have reached the end of
a paragraph.

Using other sample inputs I see there are a few issues, particularly if the text features a short paragraph or if there is more than one paragraph in the source text (leading to the trailing shorter lines reducing the overall average).

Stating Your Requirements
It's important to have a clear defintion of what you want to achieve before you start writing code, even though there are many different ways of achieving that, for instance by practicing Test-Driven Development or writing a formal specification.
The important part is that without a clear definition, you can't validate whether you're done. In your case, the question contains a description that is completely different than the code and quite unclear.
The above is vital even if you're only writing the code as an exercise for personal use or learning.
Testing and Edge Cases
In the following code:
word_in_next_line = lines[li+1].split()[0]

Why are you assuming that

there will be a next line? What if the text consists of only one paragraph?
the next line will not be empty?

These assumptions are unreasonable and when I first tried out your code on some text, it immediately threw an exception.
Naming

Be careful with historically significant terms such as ss (Google it if you don't know what I mean).

Expressive names are better than abbreviations! Replace:

ss with source_text
ll with line (this looks like the number 11!)
lens with line_lengths
avglen with average_length
maxlen with maximum_length
in the for loop, li with index and ll with line

Conclusion
Without a clear explanation of what you are trying to accomplish, how the input data looks and how you define a paragraph, it's impossible to show you a better way of solving the problem.


Less insane interface design for a trigger component for T types? Disclaimer: I just asked this on the regular SE, but was suggested to post it in here since it's kind of a code review.

I've recently been playing around with component frameworks, and I'm trying to create a basic trigger component. The component should be able to take one (or more) pair of values that can be compared against each other, triggering upon certain conditions.

The value pair should be of a generic type, I suggest an interface like IComparable. The TriggerComponent itself cannot be templated (i think?), as the component system must register it and would not be able to do so without supplying type information via angle brackets. Here's my current prototype version. It works, but some awkward issues that I'll explain below:

  /* interface IComparable.h */
  class IComparable
  {
  public:
    virtual ~IComparable() {}

    virtual bool lessOrEqual(const IComparable& other) const = 0;
  };

  /* Derived type container, intended for primitive values like int, float etc */
  template<class T>
  class NumberType : public IComparable
  {
  public:
    NumberType(const T& number) : m_number(number) {}
    bool lessOrEqual(const IComparable& other) const
    {
      NumberType& nt = (NumberType&)other;
      return m_number <= nt.m_number;
    }

    const T& m_number;
  };

  /* Component with threshold/trigger values made up by number types, but also objects of IComparable */
  class TriggerComponent : public artemis::Component
  {
  public:
    TriggerComponent(const IComparable& threshold, const IComparable& triggerValue)
      : m_thresholdValue(threshold), m_triggerValue(triggerValue) {}

    const IComparable& threshold() const { return m_thresholdValue; }
    const IComparable& triggerValue() const { return m_triggerValue; }

    void execute() const { qDebug() << "execute!"; }

  private:
    const IComparable& m_thresholdValue;
    const IComparable& m_triggerValue;
  };

The triggerValue parameter should be a reference as it is supposed to be monitored and checked against the threshold. Threshold should ideally be a copy, and not refer to anything. I would ideally like to have IComparable/NumberType as structs as it would make it easy to reference or copy as needed, but I don't think it is possible due to the pure interface.. As they're both reference values, I'm in a lot of cases forced to allocate heap memory, which i'd like to avoid for simple types.

If I had a cube in a 3D world with an ongoing scaling reduction, here's how I'd use the TriggerComponent to detect when it's X component reaches 1.0f:

    Entity* cubeEntity = /* omitted */
    ScaleComponent* scaleComp = /* omitted*/
    float* cubeScaleMinThreshold = new float(1.0f);
    NumberType<float>* threshold = new NumberType<float>(*cubeScaleMinThreshold);
    NumberType<float>* currScale = new NumberType<float>(scaleComp->getx());
    cubeEntity .addComponent(new TriggerComponent(*threshold, *currScale));

I need the flexibility to create components on the fly, and I'd like to pass stack-created values as copies rather than passing raw pointer refs, but I'm not exactly sure how I can make it work in my current interface setup. I don't see how I can make generic comparisons between values (of same type) without one, but that seems to also require members to not be abstract value types.

I would be very appreciative on possible changes to make the design less insane. Maybe I'm just overlooking an obvious simple approach?

PS. I know raw pointers set up like I just did, leak like a 2 year old. It's to show why the design is terrible! :)

Having thought a little bit on the problem, I've come up with a solution I think satisfy my goal without being too awkward or introducing gotchas with raw pointers and ownership. Below is my updated code and as always, I would appreciate any feedback or tips on improvement.

  class IComparable
  {
  public:
    virtual ~IComparable() {}
    virtual bool lessOrEqual() const = 0;
    virtual bool greaterOrEqual() const = 0;
    virtual bool equal() const = 0;
    virtual bool lessThan() const = 0;
    virtual bool greaterThan() const = 0;
  };

  /* trigger/threshold set of any type supporting the comparison operators. Can create new set by adhering to the interface*/
  template<class T>
  class ComparableTriggerSet : public IComparable
  {
  public:
    ComparableTriggerSet(std::shared_ptr<T> threshold, const T& trigger) : m_threshold(threshold), m_trigger(trigger) {}
    bool lessOrEqual() const { return m_trigger <= *m_threshold; }
    bool greaterOrEqual() const { return m_trigger >= *m_threshold; }
    bool equal() const { return m_trigger == *m_threshold; }
    bool lessThan() const { return m_trigger < *m_threshold; }
    bool greaterThan() const { return m_trigger > *m_threshold; }

  private:
    std::shared_ptr<T> m_threshold;
    const T& m_trigger;
  };

  /* supported operators */
  enum CompareOperator { LessOrEqual, GreaterOrEqual, Equal, LessThan, GreaterThan };

  /* TriggerComponent - getting checked at regular intervals by the TriggerSystem */
  class TriggerComponent : public artemis::Component
  {
  public:
    TriggerComponent(std::shared_ptr<IComparable> comparableTriggerSet, CompareOperator compareOperator)
      : m_comparableTriggerSet(comparableTriggerSet), m_compareOperator(compareOperator) {}

    void check() const
    {
      bool condition = false;
      switch(m_compareOperator)
      {
        case LessOrEqual:
          condition = m_comparableTriggerSet->lessOrEqual();
          break;
        case GreaterOrEqual:
          condition = m_comparableTriggerSet->greaterOrEqual();
          break;
        case Equal:
          condition = m_comparableTriggerSet->equal();
          break;
        case LessThan:
          condition = m_comparableTriggerSet->lessThan();
          break;
        case GreaterThan:
          condition = m_comparableTriggerSet->greaterThan();
          break;
        default:
          assert(false && "unsupported operator enum");
          break;
      }

      if(condition)
        execute();
    }

    /* supposed to invoke an event or maybe call a script or something similar */
    void execute() const
    {
      qDebug() << "execute!";
    }

  private:
    std::shared_ptr<IComparable> m_comparableTriggerSet;
    CompareOperator m_compareOperator;
  };

I would then add the component in my executable like so:

  artemis::Entity& ent = /* omitted */
  ScaleComponent* scaleComp = /* omitted */
  std::shared_ptr<float> threshold = std::make_shared<float>(1.0f);
  std::shared_ptr<ComparableTriggerSet<float>> triggerSet = std::make_shared<ComparableTriggerSet<float>>(threshold, scaleComp->getx());
  ent.addComponent(new TriggerComponent(triggerSet , CompareOperator::LessThan));

I think the updated code solves my original issues fairly well. I have thus far not encountered any problems with it, and I can add TriggerComponents without worry of whether threshold value is getting off the stack, cleaned up properly etc.


Simple Rock Paper Scissors I made a Rock Paper Scissors game. It works fine but I would like to know how can I improve it further.
#include <iostream>
#include <algorithm>
#include <string>
#include <random>
#include <array>
#include <map>
#include <limits>

namespace
{
    enum Winner { Tie, Player, Computer, WinnerCount };
    enum Items { Rock, Paper, Scissors, ItemsCount };

    template<typename T, std::size_t N>
    using Matrix = std::array<std::array<T, N>, N>;
}

std::string user_choice(const std::array<std::string, Items::ItemsCount>& data)
{
    std::string result;
    static auto comp = [&result](const std::string& str) { return str == result; };
    bool is_input_valid = false;

    do
    {
        std::cout << "Enter your choice, rock, paper, or scissors: ";
        std::getline(std::cin, result);

        is_input_valid = !(std::cin.fail() || std::none_of(data.begin(), data.end(), comp));

        if (!is_input_valid) {
            std::cout << "Not valid input.\n";
        }

        std::cin.clear();
        std::cin.ignore(std::cin.rdbuf()->in_avail());
    } while (!is_input_valid);

    return result;
}

bool play_again()
{
    char result;
    bool is_input_valid = false;

    do
    {
        std::cout << "Do you want to play again? [y/n]: ";
        std::cin >> result;

        result = std::toupper(result);

        is_input_valid = !(std::cin.fail() || (result != 'Y' && result != 'N'));

        if (!is_input_valid)
        {
            std::cout << "Not valid input.\n";
        }

        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } while (!is_input_valid);

    return result == 'Y';
}

int main()
{
    // Set up game
    const Matrix<Winner, Winner::WinnerCount> table
    {
        {  // Rock      Paper      Scissors
            { Tie,      Computer,  Player   }, // Rock
            { Player,   Tie,       Computer }, // Paper
            { Computer, Player,    Tie      }, // Scissors
        }
    };

    const std::array<std::string, Items::ItemsCount> data
    {
        "rock",
        "paper",
        "scissors"
    };

    std::map<std::string, Items> binding_items
    {
       { data[Items::Rock],      Items::Rock     },
       { data[Items::Paper],     Items::Paper    },
       { data[Items::Scissors],  Items::Scissors },
    };

    const std::array<std::string, Winner::WinnerCount> winner_result
    {
       "It's a tie!\n\n",
       "You win!\n\n",
       "You lose!\n\n"
    };

    std::mt19937 engine{ std::random_device()() };
    auto dist = std::uniform_int_distribution<>(0, Items::ItemsCount - 1);

    // Game loop
    do
    {
        std::cout << "\n\n\tRock Paper Scissors Game\n\n";

        const auto user_chose = user_choice(data);
        const Items player = binding_items[user_chose];

        const Items computer = static_cast<Items>(dist(engine));
        const auto computer_chose = data[computer];

        std::cout << "\n\nYou entered: " << user_chose << '\n';
        std::cout << "Computer chose: " << computer_chose << '\n';

        std::cout << winner_result[table[player][computer]];
    } while (play_again());
}

Looks pretty good at first glance! I'd say your main problem is "#define ONE 1" — you've gone out of your way to parameterize things that can't actually be changed in real life without massive changes elsewhere in the game logic. For example, you've set
enum Items { Rock, Paper, Scissors, ItemsCount };

which looks awesome... until someone decides to actually use that flexibility by changing it to
enum Items { Rock, Paper, Scissors, Lizard, Spock, ItemsCount };

and suddenly nothing compiles anymore. (They also have to change the local variables table and data and binding_item inside main, and the text of the cout inside user_choice, and maybe some more stuff too. By the way: variable names are important! data and table are not good names!)
The over-parameterization antipattern tends to travel along with the std::array antipattern — see "The 'array size constant' antipattern" (2020-08-06). Somehow, people who've caught the "named constants > magic numbers" virus also tend to have caught the "std::array > core language" virus as well. Where you write
template<typename T, std::size_t N>
using Matrix = std::array<std::array<T, N>, N>;

const Matrix<Winner, Winner::WinnerCount> table
{
    {  // Rock      Paper      Scissors
        { Tie,      Computer,  Player   }, // Rock
        { Player,   Tie,       Computer }, // Paper
        { Computer, Player,    Tie      }, // Scissors
    }
};

an expert C++ programmer would probably just write
Winner table[3][3] = {
    // Rock      Paper      Scissors
    {  Tie,      Computer,  Player   }, // Rock
    {  Player,   Tie,       Computer }, // Paper
    {  Computer, Player,    Tie      }, // Scissors
};

Incidentally, did you notice your bug above? You dimensioned your table by WinnerCount, but you index into it using values of Item. You're simply getting lucky that WinnerCount (win, lose, tie) happens to be the same as ItemCount (rock, paper, scissors).

Be aware that
std::mt19937 engine{ std::random_device()() };

is a relatively low-entropy way to initialize a Mersenne Twister: it has 19937 bits of state, and you're seeding it with only 32 random bits. But C++ doesn't offer any concise way to seed a PRNG properly, so actually what you've got is the state of the art.

const Items computer = static_cast<Items>(dist(engine));

Throughout, you use plural words where singular would be more appropriate, and relatively abstract nouns (data, table, computer) where more concrete ones would be appropriate. I'd write:
Item computers_choice = static_cast<Item>(dist(engine));

indicating that what we've got now is not a computer but rather the computer player's choice of what to throw; and it is not multiple Items but rather a single Item. (I'd probably rename Item to Gesture, too.)

Your user_choice function returns std::string, which you then have to parse again in main. It should just return the Item it extracted, directly, instead of the string.
Also, the logic around the is_input_valid boolean seems pretty baroque. Think about how the code could be simplified by using a return or break statement inside the loop.
if (std::getline(std::cin, result)) {
    if (map_of_strings_to_gestures.contains(result)) {
        return map_of_strings_to_gestures.at(result);
    }
}
std::cout << "Not valid input.\n";
// and go around again

Also, try hitting Ctrl-D (or Ctrl-Z on Windows) at this prompt. That'll close stdin, which makes cin.fail() true, which means the input isn't valid... and then your code just goes into an infinite loop, doesn't it? I think you actually want to break out of the loop when you see EOF or an error — not stay in the loop!

For configuring the gestures, I think you should investigate X-macros. Here's my take: https://godbolt.org/z/8qhdcPWT5 The entirety of the "configuration" for the game is expressed in a single table at the top of the code:
#define GESTURES \
    X(Rock,     "rock",     BEATS(Scissors)) \
    X(Scissors, "scissors", BEATS(Paper)) \
    X(Paper,    "paper",    BEATS(Rock))

and I've also tested it with this configuration:
#define GESTURES \
    X(Rock,     "rock",     BEATS(Scissors) BEATS(Lizard)) \
    X(Scissors, "scissors", BEATS(Paper) BEATS(Lizard)) \
    X(Paper,    "paper",    BEATS(Rock) BEATS(Spock)) \
    X(Lizard,   "lizard",   BEATS(Spock) BEATS(Paper)) \
    X(Spock,    "spock",    BEATS(Scissors) BEATS(Rock))

(My version also eliminates the dependencies on <map>, <algorithm>, and of course <limits>.)

An obvious "next step" for this program would be to refactor it so that you can print a customized verb for each outcome:
Enter your choice (rock, scissors, paper): rock
You entered: rock
Computer chose: paper
Paper covers rock — you lose!

Enter your choice (rock, scissors, paper): scissors
You entered: scissors
Computer chose: paper
Scissors cuts paper — you win!

and so on.


Given an array of N elements, answer Q queries asking if there exist two elements from two specified range with a given XOR value We have array of N (<=10^5) elements with Q(<=10^5) queries.

  Each query is of type: p q r s x, where we have to find if
  there exist a element from array in range [p,q] and an element in
  [r,s] whose xor is equal to X. If exists, print "true" else
  "false".

Constraints:

1 <= N <= 10^5
1 <= p,q,r,s <= N
1 <= A[i] <= 10^5
Example:
Array : 1 2 3 4 5 6
Query : 1 3 4 6 5
Output: true.

1 from range [1,3] and 4 from range [4,6] has an XOR value equal to X=5.

I tried to solve it by loading the second sub array into a hashmap then XORing x with each element from first array and if the result exists in hashmap answer is yes.

But this \$O(n)\$ solution for each query isn't sufficient to pass. I am looking for ideas for how I can achieve this in possible \$O(logn)\$ or \$O(1\$) time for each query, or if it is possible to answer queries offline using MO's algorithm in \$O(sqrt(n))\$ time.

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
int a[100001];

bool query(int p,int q,int r,int s,int x)
{
    unordered_map<int,int> mp;
    for(int i =r;i<=s;i++)
    {
        mp[a[i]]=1;
    }
    for(int i =p;i<=q;i++)
    {
        if(mp.count(a[i]^x) > 0)
        {
            return true;
        }
    }
    return false;
}

int main()
{
    int n,q;
    cin>>n>>q;
    for(int i =0;i<n;i++)
    {
        cin>>a[i];
    }
    while(q--)
    {
        int p,q,r,s,x;
        cin>>p>>q>>r>>s>>x;
        // -1 because they are 1-indexed
        if(query(p-1,q-1,r-1,s-1,x))
        {
            cout<<"true\n";
        }
        else
        {
            cout<<"false\n";
        }
    }

    return 0;
}

Avoid non-standard headers. Especially giant composite-headers like <bits/stdc++.h>. They make your program unportable and/or  slow compilation down.
You are using using namespace std;.
That's a bad idea, read "Why is “using namespace std;” considered bad practice?".
Aside from its obscuring impact if you ever used the typedefs, vi and ll are unused. Remove to minimize confusion.
Do you know std::unordered_set? That's better for representing a set than std::unordered_map...
Anyway, you should change the algorithm but we'll get there later.
You should consider whether swapping the ranges can speed things up.
The conditional operator (ternary operator, exp ? true_exp : false_epp) is perfect for choosing the value to use.
You never check for input-failure or inputs being out-of-range.

Now the algorithm:

Consider initializing a std::unordered_multimap, or if duplicates are plentiful a std::unordered_map of sorted std::vector from the input-array.
Then for each query check every element in the smaller range whether element xor x is in the whole array, and filter that down to the second range.


Inferring Memory Alignment The following code is intended to infer the alignment of double.
My questions include:

Is there a better to do this? Either by refining the code or using an entirely different approach.

Under what (reasonable) circumstances could this not work?

Under what (plausible) circumstances could this not work? See below.

What is the actual or practical complete list of types I would need to do this with to determine universal alignment?
I think it's short,int,long,long long,float,double, long double, void*.
Specifically char can't be have a alignment constraint (or c-strings are broken!), unsigned can't be different from signed (or type-aliasing is broken).
Is there any reason why void* can't stand in for all pointer alignments?

#include <stdio.h>

// *********************************************************************** //
//WARNING: Do not allow this translation unit to be compiled under the
//#pragma pack directive or similar unless whole application is compiled the same way.
// *********************************************************************** //

typedef struct {
    char mWedge;//Wedges the member off alignment with the start of the struct.
    double mMember;//Member with type we're going to get alignment of.
} DoubleAligned;

const size_t getDoubleAlignment(void){
//A bit of pointer shennanigans to count the padding between mWedge & mMember.
//See text.
    const DoubleAligned lSpecimen;
    const size_t lOffset= (char*)&(lSpecimen.mMember)-(char*)&(lSpecimen.mWedge);
    return lOffset;
}

int main(void) {
    printf("Alignment : %zu\n",getDoubleAlignment());
    return 0;
}

Expected output on platform where double has 4-byte alignment:

Alignment : 4

Expected output on platform where double has no alignment (AKA 1-byte alignment:

Alignment : 1

NB: If the compiler 'packs' structures by default and just 'takes the hit' on slicing and shuffling to get them into hardware alignment, I don't mind getting an output of 'Alignment : 1'. I'm interested in how the platform (programming environment presented to me) is aligned not trying to infer underlying hardware design.
Reasoning
The C specification (C99 to be specific) makes the following commitments:

malloc(.) returns a universally aligned address.

Structures can pad between members and at the end but specifically not the beginning.

Arrays of adjacent structures must be aligned in a way compatible with their members.

Members will be laid out in the order they are declared.

So the compiler has to place mMember in an aligned position after mWedge itself aligned to the start of DoubleAligned. The C specification doesn't further constrain why or how structures are padded but there appears to be no normal reason to pad them other than minimally to satisfy 2, 3 & 4 above.
Hence my question about 'plausible' circumstances. Formally the compiler can do what it likes including adding arbitrary space into structures (but not at the beginning) for reasons that have nothing to do with alignment - maybe debug info or overwrite detection. Does that actually happen?
I'm not entirely sure about void* standing in for all pointer types. void* must have the lowest-common-factor alignment of all the pointer types (not the types pointed to!).
Bonus Note:
On many platforms I can get away with:
const size_t getDoubleAlignment(void){
//A bit of pointer shennanigans to count the padding between mWedge & mMember.
//See text.
    const DoubleAligned* lSpecimen=NULL;
    const size_t lOffset= (char*)&(lSpecimen->mMember)-(char*)&(lSpecimen->mWedge);
    return lOffset;
}

But I believe this is formally undefined because it performs arithmetic on NULL.
Final Note: Why do you need to know? (someone will ask) Suppose I need a portable alternative malloc(.) implementation that uses pre- and post- 'overhead' areas. I could implement it around the native malloc(.) but would need to know what "universal alignment" meant to comply with the C standard for malloc(.) to carve out a universally aligned return value.

Is there a better to do this (infer the alignment of double)?

Curious as to why size_t type is used.  The first choice should be ptrdiff_t.

  When two pointers are subtracted, ... and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header.  C11dr §6.5.6 9

Since alignment is certainly something less than 127, any integer type will do for our purposes.  Could use int, unsigned, size_t.

The cast of &(lSpecimen.mWedge) is redundant other than to remove the const

My GCC 4.5.3 compiler says the const on the return type is ignored.

int getDoubleAlignment(void) {
  const DoubleAligned lSpecimen;
  const int lOffset = (char*)&(lSpecimen.mMember) - &(lSpecimen.mWedge);
  return lOffset;
}

Under what (reasonable) circumstances could this not work?  (Nothing to add)
Under what (plausible) circumstances could this not work? (Nothing to add)

What is the actual or practical complete list of types I would need to do this with to determine universal alignment?

Rather than use double, use max_align_t if available.  max_align_t is not in C99.

  "... max_align_t which is an object type whose alignment is as great as is supported by the implementation in all contexts ..."  C11dr §7.19 2

Otherwise instead of double use a union of all non-narrow types:

union {
  int i;
  long l;
  long long ll;
  float f;
  double d;
  long double ld;
  float _Complex fc;
  double _Complex dc;
  ptrdiff_t pd;
  // Suspect the below are the only 4(5) code may truly need
  long double _Complex ldc;
  void *p;
  void (*pf)();
  intmax_t im;
  // C11
  max_align_t ma;
} OneOfEach;

void* might be narrower than void (*pf)() so void* will not work for all pointers.


Calisthenics objects, and primitive wrapped in Objects I m working on calisthenics objects and I'm actually having some troubles while trying to follow the calisthenic objects rules.

In fact, I m stuck with the one telling that we have to wrap all the primitives inside of objects.

Context

I'm having a Euro object that looks like :

public class Euro {

    private double amount;

    public Euro(double amount) {
        this.amount = amount;
    }

    @Override
    public boolean equals(Object obj) {
        Euro other = (Euro)obj;
        return other.amount == amount;
    }

    // Problems come here
    public Euro multiply(double priceValue) {
        Euro newAmount = new Euro(amount * priceValue);
        return newAmount;
    }

    public Euro add(Euro valueToAdd) {
        Euro newPrice = new Euro(amount + valueToAdd.amount);
        return newPrice;
    }
}

And I m having a Discount class. In fact, we can apply Discount on product, the the amount we obtain is a Euro :

public class Discount {

    private double value;

    public Discount(double theValue) {
        value = theValue;
    }

    public Euro apply(Euro price) {
        return price.multiply(value);
    }
}

Problem

My problems appear on the multiply method of the Euro object.

In fact, currently, I m accepting a double as parameter, and it doesn't follow the rule of wrapping all primitives in objects... Moreover, a "double" in a business context doesn't mean anything at all. I m a little bit stuck with this example and don't know how to bypass this.

Moreover, I don't want to use getter / setter on this implementation...

Any suggestions ?

That cannot work with this Object hierarchy. You have a contradiction in your katas, that requires some messy stuff.

Here's an extract of the katas of your previous similar Question (emphasis mine):

  One level of indentation per method
  Don’t use the ELSE keyword
  Wrap all primitives and Strings
  First class collections
  One dot per line
  Don’t abbreviate
  Keep all entities small (50 lines)
  No classes with more than two instance variables
  No getters/setters/properties

You're dealing with two double values of distinct meaning (a discount rate and a cost). Because of kata Wrap all primitives, you wrap them both in two, distinct object.

Now you need these primitives (the doubles) to interact (multiply). No Object  can access both values, since the kata No getters prevents one from accessing the other's internal values!

A Solution

You've successfully made two primitives interact elsewhere. It was in the Euro class:

public Euro add(Euro valueToAdd) {
    Euro newPrice = new Euro(amount + valueToAdd.amount);
    return newPrice;
}

A primitive wrapper is able to make interactions with a primitive wrapper of the same type, or with a subclass of it. Then that is what you should do: all double wrappers that will want to interact must extend a common double wrapper. (Note 1: I didn't spot any rule against subclassing, yet you did not subclass anything. Note 2: does subclassing bypass kata No classes with more than two instance variables? Don't need it, just curious).

So here's the code:

MonetaryQuantity.java (Edit: Changed the name, fits better) is a parent class to all stuff that will ever interact with money etc.)

public class MonetaryQuantity {
    protected double value; // Can be accessed by any Money-related class
    public MonetaryQuantity(double theValue) {
        value = theValue;
    }
}

Euro.java:

public class Euro extends MonetaryQuantity{
    public Euro(double amount) {
        super(amount);
    }
    public Euro apply(Discount discount) {
        Euro newAmount = discount.applyOn(this);
        return newAmount;
    }
    public Euro add(Euro valueToAdd) {
        Euro newPrice = new Euro(value + valueToAdd.value);
        return newPrice;
    }
}

Discount.java:

public class Discount extends MonetaryQuantity{
    public Discount(double theValue) {
        super(theValue);
    }
    public Euro applyOn(Euro price) {
        // Discount can access Euro.value because both handle money (similar business sphere)
        return new Euro(price.value * value);
    }
}

Notes on style

Why do you apply a Euro on a Discount? Usually, we apply a Discount on a Price. I prefer price.apply(discount). I kept discount.applyOn(price).

Naming value on Euro is a bit clumsy. It may be a cost, or a price, those things are different. Maybe two subclasses?

Naming value on Discount is just bad. It should be a rate. The Object might even be called a DiscountRate, because you could have an AbsoluteDiscount (-10€). Discount would be an interface with a Euro applyOn(Euro price) method. Note I moved the implementation of the discount from the Euro class to the Discount class for just that reason. Euro just forwards it to Discount.

Note: with these Katas, I cannot extract an add and a multiply method into the wrapper class (although I would really like it!) because it would have to return the proper Wrapper sub-class (not the primitive result). It would only work with C-style result-passing in parameters AND require a setValue():

public class MonetaryQuantity {
    public <T extends MonetaryQuantity> T add(MonetaryQuantity valueToAdd, T returnValue) {
        double newValue = value + valueToAdd.value;
        returnValue.set(newValue); // This is against a kata!
        return newValue;
    }
}

This is all quite frustrating.

The equals() method

It's broken everywhere. It fails with ClassCastExceptions, NullPointerExceptions etc. Make instanceof checks and handle the mismatch cases properly.


Scala BitSet implemented with Java BitSet, for use in Scala Enumerations to replace ValueSet Due to a performance profiling hotspot detailed here, I implemented my own BitSet using Java's BitSet.  This is intended to replace the Enumeration.ValueSet.  However, it's a bit awkward to use, primarily due to my likely misunderstanding of the relationships between the Enumeration class, Enumeration type and concrete Enumeration object.

In my enumeration objects, I have to have code like this:

type BitSet = alder.BitSet[this.type]
val empty = alder.BitSet[this.type]()

Elsewhere, I need to do things like this:

alder.BitSet.fromBitMask[SomeEnumeration.type](...)

For mkString I need to actually pass in the enumeration object itself.  Is there any way to make this entire edifice a little more user-friendly?

package alder

import scala.language.implicitConversions

class BitSet[E <: Enumeration](val bits: java.util.BitSet) {

  def isEmpty: Boolean = bits.isEmpty

  def nonEmpty: Boolean = !isEmpty

  override def hashCode = bits.hashCode

  override def equals(o: Any) = o match {
    case that: BitSet[E] => this.bits equals that.bits
    case _ => false
  }

  def union(that: BitSet[E]): BitSet[E] = {
    var newBits = bits
    newBits.or(that.bits)
    new BitSet[E](newBits)
  }

  def |(that: BitSet[E]): BitSet[E] = union(that)

  def |(v: E#Value): BitSet[E] = union(BitSet(v))

  def intersection(that: BitSet[E]): BitSet[E] = {
    var newBits = bits
    newBits.and(that.bits)
    new BitSet(newBits)
  }

  def &(that: BitSet[E]): BitSet[E] = intersection(that)

  def &(v: E#Value): BitSet[E] = intersection(BitSet(v))

  def contains(v: E#Value): Boolean = bits.get(v.id)

  def containsAll(that: BitSet[E]): Boolean = intersection(that) == that

  def containsAny(that: BitSet[E]): Boolean = intersection(that).nonEmpty

  def toBitMask(): Array[Long] = bits.toLongArray

  def mkString(e: E, sep: String): String =
  {
    val vs = e.ValueSet.fromBitMask(toBitMask())
    vs.mkString(sep)
  }

}

object BitSet {

  def apply[E <: Enumeration](): BitSet[E] = new BitSet[E](new java.util.BitSet)

  def apply[E <: Enumeration](vs: E#Value*): BitSet[E] = {
    var bits = new java.util.BitSet
    for (v <- vs) {
      bits.set(v.id)
    }
    new BitSet[E](bits)
  }

  def fromBitMask[E <: Enumeration](mask: Array[Long]): BitSet[E] =
    new BitSet[E](java.util.BitSet.valueOf(mask))

}

After studying your code for a good long while, I realized that the reason you haven't gotten an answer is that there isn't really much to say about your code. Well done!

I would recommend adding some thorough ScalaDoc though. It has been my experience that Scala library developers have far too much faith in the ability of library users to magically understand what they really meant. Examples are wonderful things.