Implementing a thread safe log class with simple functionality

One of the things you can do to get some performance back (albeit not a lot, but still more than none) is rewrite Save to have one responsibility.

As it stands now, Save has several responsibilities. It's responsible for:

Checking if the buffer is of sufficient length to be saved.
Validating that _logDir ends with a \.
Creating the _logDir directory.
Coming up with the filename for the log file.
Saving the buffer to disk.
Clearing the buffer after saving.

The Save method should only be responsible for saving (and maybe clearing) the buffer. If you move the if check outside to the Log method, you remove a (minor) bit of overhead.

A better style would be to create a method SaveIfFull which does the if-check, then calls Save which actually saves the buffer.

You have a:

public static string _logDir = "C:\\Logs";

Which is generally frowned upon. The best-practice for public members is PascalCase with no leading characters. So, instead, it should be:

public static string LogDir = "C:\\Logs";

Never omit braces from if statements, and never one-line them. Adding braces won't prevent bugs, but it will help prevent bugs.

if (!_logDir.EndsWith("\\")) _logDir += "\\";

Should be rewritten as:

if (!_logDir.EndsWith("\\"))
{
    _logDir += "\\";
}

Likewise, you should make _logDir (which we to LogDir) a property, with a private backing field.

private static string _logDir = "C:\\Logs\\";
public static string LogDir
{
    get
    {
        return _logDir;
    }
    set
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentException("The specified value must not be null, whitespace, or an empty string.", "value");
        }

        _logDir = value;

        if (!_logDir.EndsWith("\\"))
        {
            _logDir += "\\";
        }
    }
}

You can also add other validation logic in there as you need, but this way it helps separate responsibilities further.

To get rid of some of the other additional responsibilities Save has, we can consider a method GetLogFileName(DateTime loggedAt) which would return the filename, then Save would call string todayFileName = GetLogFileName(DateTime.Now) or string todayFileName = GetLogFileName(DateTime.UtcNow) as appropriate.

If you have C#6.0 a few of these tasks become easier/simpler:

Path.Combine(_logDir, ("Log" + DateTime.Now.ToString("yyyy-MMMM-dd") + ".txt")); simplifies to: Path.Combine(_logDir, $"Log{DateTime.Now.ToString("yyyy-MMMM-dd")}.txt");
You can replace "value" at the end of ArgumentException with nameof(value). (Which allows you to refactor that message cleanly.)

As far as your primary concerns:

Yes, the idea of the lock is to mark a shared resource as "in-use" so that threads know to wait on each other before they can proceed. You could, however, replace it with a bool instead of an object for smaller overhead.
You could have performance implications by the lock, but that's the downside of multithreading: somewhere you will have a bottleneck from context-switching, et al.
That is beyond the scope of Code Review.

Another concern: if there is a substantial delay between messages, it may occur that the log is never written to before the application is closed (or messages are left in the buffer), this can be alleviated by scheduling a Timer to save the log at periodic intervals as well, so that if there is a substantial delay the log is saved anyway.


Dictionary algorithm, computing all case options

You are absolutely correct - it is binary counting. In the case of antidiseastablismnetarianism you'd need to produce \$2^{28}\$ words, that is quite a few. No surprise you are stuck, but unfortunately there is no real way around.

You may streamline the word generation a bit (most likely it wouldn't affect the bottom line) by doing a more natural binary counting. For example,

    int length = 1 << word.length;

    for (int counter = 0; counter < length; ++counter) {
        for (int pos = 0; pos < word.length; ++pos) {
            binaryList[pos][counter] = (counter & (1 << pos))?
                toUpper(word[pos]): toLower(word[pos]);
        }
    }


Generally this is very good code, but I try to be thorough when reviewing so I've listed every minor point that I could think of.

It looks like you write OO code in other places, but you chose to make your bootstrap procedural.  Believe it or not there are benefits to an OO bootsrap!  You can define methods for different parts of the system that you want to bring up.  There will always be some procedural code required to call the bootstrap, but it could look more like this:

$bootstrap = new Bootstrap();
$bootstrap->initializeAutoload();
$bootstrap->initializeErrorReporting();
$bootstrap->initializeRouter();

As GordonM said, use spl_autoload_register.

You are tightly bound to the config class by your static calls to it.  This makes it hard to test your bootstrap.  It is understandable in the bootstrap as you have only just brought the autoload up.  Keep reading and at the end I'll tell you what I recommend on that.

Personally I don't like the error control operator @.  I find it hard to understand what will happen when your server redirect url is not defined.  This is very minor, but I would use:

if (isset($_SERVER['REDIRECT_URL']))
{
    $url_object = $router->parse_request_url($_SERVER['REDIRECT_URL']);
}
else
{
    $url_object = $router->parse_request_url('');

}

$namespace and $class are misleading to me, I would rewrite those:

$class_name = '\baremvc\controllers\\' . $url_object->Controller;
$controller = new $class_name;

ex::show_404 couples your code tightly to the ex class.  This makes it harder for you to test this code as now you require a stub for ex as well as config.  You also call new to create a variable controller class, that would make it hard to test.

Other good things that you can do in the bootstrap are:  set_error_handler, set_exception_handler, register_shutdown_function.

Now about some of the coupling in this code (to config, ex and the variable controller class).  This is an issue if you want to test this code or have it so that it is reusable (You are going to need config and ex if you want to reuse it as it is).  You may be happy enough to leave it as it is.  That would be a valid choice and one many people would take.  Many people should stop reading now (I won't be offended if you also ignore the following).

Now, if you want to get around it a little.  All static calls and calls to new bind the calling code to the class that they are calling.  Look at the following and answer for yourself how tightly they bind the code to the class:

config::enable_sessions
$object->enable_sessions
$configObject = new Config();
$configObject = $container->getNew('Config');

I believe the tightness of coupling is - High (need config class with enable_sessions), Low (need any object with enable_sessions), High (need config class), Low (need an object with getNew).

My recommendation would be that if you are going to bind your Bootstrap to anything it should be a container class, because from that you can get any other object that you need.  This means you will only have to stub one class (the container) when you test, which should be simple.


I think the preferred way to handle async on the server in Meteor is to use fiber aware async functions, e.g. use the http Meteor package which gives you fiber aware "sync" style calls on the server (you write it like a sync call but it does not block the thread) and standard async callback signature on the client.

Also, I am not sure about using futures on the client, is there even a fibers environment running on the client?  Instead, I think you just pass a standard callback to Meteor.call to handle the results of the method.


Your code is easy to understand, so I can only suggest minor changes. The first thing is just a preference of mine: if a function body is nothing but a match ... with expression, I use the function keyword, instead. The second, more important recommendation is to use three clauses in the match body so you don't build a new, temporary list (hd2 :: tl) as you recurse. With both of these minor changes, sort looks like this:

let rec sort lst =
  let sorted = function
  | hd1 :: hd2 :: tl when hd1 > hd2 ->
        hd2 :: sort (hd1 :: tl)
  | hd1 :: tl ->
        hd1 :: sort tl
  | tl -> tl
in
if lst = sorted then
    lst
else
    sort sorted

As the list gets more and more sorted, the second pattern gets matched more often and simply travels down the list. Your version continues to build a new list -- even when the list is sorted.

One other thing: OCaml has an equality operator that tests for physical equality (in addition to structural equality.) So we can avoid building a new list in the second case, if it's not necessary:

| (hd1 :: tl) as lst ->
    let tl' = sort tl in
    if tl' == tl then
        lst
    else
        hd1 :: tl'

Both these changes will prevent a lot of temporary objects from being created. Unfortunately, it's still a bubble sort, so it's never going to be a speed-demon. :D


The variable names c, d, and e are too cryptic.  (f is fine, because it's a customary variable for a file.  In my solution below, I use c consistently for characters during iteration, which is also acceptable.)

Why do you normalize the case using line.lower(), when the sample output suggests that uppercase output is preferred?

In my opinion, the regular expression is overkill here.

The challenge is ambiguous as to what exactly constitutes "15% in a given passage of text".  Does the denominator include the spaces and punctuation?  That's debatable.  Should the denominator include the trailing newline?  Probably not, but you should be aware that you did.

Personally, I'd prefer to collect all of the super freqs using a list comprehension, instead of checking for the if (c == 0): … case.  In any case, there shouldn't be parentheses there in standard Python style.

from collections import Counter

with open('prob2.in') as f:
    for line in f:
        counts = Counter(c for c in line.upper() if 'A' <= c <= 'Z')
        super_freqs = [c for c, n in counts.items() if n / len(line) > 0.15]
        if not super_freqs:
            print('There are no super freqs.')
        else:
            for c in super_freqs:
                print('{0} is a super freq.'.format(c))


You have the right idea.  There are a few details that could be tightened up.

In the main driver:

command is not really what I would consider a command; it's just a useless counter.  By convention, unused variables should be named _.
temp is always a poor variable name.  In this case, command would be a better name than temp.  However, I don't think you need to give it a name at all — just write input().split().  The .strip() is superfluous, since .split() will discard leading and trailing whitespace anyway.  You don't need to convert strings to strings using str().

Naming and parameter-passing for the commdr() function could be improved as well.  Here's how I would write it:

def execute(lst, cmd, *args):
    if cmd == 'insert':
        lst.insert(int(args[0]), int(args[1]))
    elif cmd == 'print':
        print(lst)
    elif cmd == 'remove':
        lst.remove(int(args[0]))
    elif cmd == 'append':
        lst.append(int(args[0]))
    elif cmd == 'sort':
        lst.sort()
    elif cmd == 'reverse':
        lst.reverse()
    elif cmd == 'pop':
        lst.pop()
    else:
        print("Command not recognized!")

lst = []
for _ in range(int(input())):
    execute(lst, *input().split())

Bonus golfed solution

If you have absolutely no concern for validation or security, you could take advantage of the fact that most of the commands look just like existing methods in Python's list.

class ListInterp(list):
    def print(self):
        print(self)

    def execute(self, cmd, *args):
        getattr(self, cmd)(*map(int, args))

lst = ListInterp()
for _ in range(int(input())):
    lst.execute(*input().split())

I'm not saying that this is good code… I just thought I would mention that there is a quick-and-dirty solution.


Getting database values grouped in an array

SQL query

Of course, all the data calculations should be done on the database side. So the main improvement would be an SQL query like this

select upper(date_format(dateoforder, "%b")), count(1)
from salessummary group by month(dateoforder);

PDO magic

Next, let's utilize the PDO's magic constant that can load your data into the neat associative array, PDO::FETCH_KEY_PAIR, with month abbreviations as keys and order count for the given month as values

So our code would be

$thisyear =  date("Y");
$sql = "select upper(date_format(dateoforder, "%b")), count(1)
        from salessummary group by month(dateoforder) WHERE dateoforder LIKE ?";
$stmt = $conn1->prepare($sql);
$stmt->execute(array("$thisyear%"));
$data = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

Data gathering

It will give us the information for all the data that exists in the database, but with obvious gaps. To fill them, let's run a simple loop

$result = [];
foreach (range(1,12) as $num) {
    $mon = strtoupper(date("M", strtotime("$thisyear-$num-15")));
    $result[$mon] = $data[$mon] ?? 0;
}

and then assemble the final data structure

$datayearly = array(
    'labels' => array_keys($result),
    'series' => array(array(
        'name' => 'series-1',
        'data' => array_values($result)
    ))
);

Note that the null coalesce operator (i.e. ??) exists in PHP7 only. If your PHP version is outdated, then you could use the old form,

     $result[$mon] = isset($data[$mon]) ? $data[$mon] : 0;


Here are several tips:

Use OOP - this way you could start the session only once
Hash your passwords - this way no one can steal it from the db, or at least the chance is lower
Use MVC - separate your HTML from the PHP code
Move your db connect credentials to the .ini file - this way it could be easily changed and .ini files can be cached by the server

Feel free to check my code for user authorization here in my pet project.


A simple shellcode that will kill all your processes GNU/Linux x86_64

Now I would like to know, can it be done in some better way? It contains 13 bytes.

From this I conclude that by better you mean shorter.

You can easily bring this down to 11 bytes if you duplicate the method that was used to fill RSI for the setup of RAX.

push 0x3e
pop  rax
dec  rdi
push 0x9
pop  rsi
syscall

The instruction dec rdi depends on the existing value of RDI.
If you know that its lowest 32 bits are non-zero, then you can write dec edi instead, and lose the REX.W prefix. ( -> 10 bytes)

push 0x3e
pop  rax
dec  edi
push 0x9
pop  rsi
syscall

But the most important improvement you can make is of course writing comments.
For now those numbers 0x3E and 0x09 are just magic numbers. What do they mean?
That's what everyone that reads your code is interested in knowing.


Find substring count without string functions

Efficiency

If you want to badly enough, I'm pretty sure you can improve the efficiency of your current code, at least for typical cases--but I don't think the result will be \$O(N)\$ even if you do.

For the moment, let's treat \$N\$ as the length of the string you're searching in (which I'm going to call the haystack), and \$M\$ as the length of the string you're searching for (which I'm going to call the needle).

As you've implemented it, this is an \$O(MN)\$ operation. That is, there are \$N\$ positions in the haystack where the needle could be found, and \$M\$ comparisons to verify whether you've found the needle at that location.

The obvious way to reduce the complexity would be to use something like a Boyer-Moore search. A full Boyer-Moore search is fairly tricky to get correct, but you could use (for example) Sunday's variant of Boyer-Moore-Horspool.

So, let's start by describing the basic idea of B-M searching. Unlike most string searching, B-M based searches start from the end of the needle. For example, let's assume I'm doing a search like:

Needle: abcde
Haystack: abcabcdqwerpuiasdfasdfabcdeyakkfdabcdessity

Now, if there were a match at the first position in the haystack, the first characters would obviously have to be abcde. Using your method (starting from the beginning), we'd start from the beginning of the needle, and do four comparisons before we found that this wasn't a match (i.e., the a, b and c all matched, to it wasn't until we got to the next a that we knew it couldn't match.

With any of the Boyer-Moore variants, we'd start by looking at the fifth character in the haystack. We can't have a match at the first position unless that matches. It doesn't, so we can reject the first position with only one comparison.

Now, what we'd like to do next would be to jump ahead to the next position where a match is possible. We can look at the character there (a b, if I'm counting correctly). Looking at our needle, we know that only occurs at the second position, so we can jump ahead three more, and look at that character. That's a q, which doesn't occur in the needle, so we can jump ahead 5 more characters after that. Lather, rinse, repeat.

To manage that jumping, we don't want to scan through our needle every time to find where (of if) a character occurs in it. To avoid that, we build a table of character positions. The elements in the table will be the distance each character is from the end of the needle (and if the character doesn't occur in the needle, it'll be the length of needle + 1). That'll give us the location where we need to look for our next possible match.

When/if we get to a point where we've hit a zero in the table, we do a full comparison to see if we've found a location where the needle occurs.

abcabcdqwerpuiasdfasdfabcdeyakkfdabcdessity
abcde
   abcde
        abcde
             abcde
                  abcde
                     [abcde]

Now, there is a little bit of trickiness to deal with. This occurs if the needle contains the same character at two (or more) locations. For example, if the needle were literally needle, we have three locations where an e could indicate a match.

This is where the variants start to show up. The original Boyer-Moore built a rather complex 2D table with all those possible jumps encoded into it. The variants simplify that to at least some degree, gaining quite a bit in simplicity in exchange for a loss of efficiency (that's usually fairly minor).

In the variant I prefer, we (as pointed out above) only start to do a comparison when we reach a point where we've found a 0 in the shift table. In this case, we don't need a table of other locations where that occurs. We just need one secondary jump to the next possible match location for that one character. In this case, that would be 3 because it's three characters back from the last e to the second to last e in needle.

Looking at overall complexity, this can be a lot lower, especially if our needle is long and consists of unique characters. On the other hand, if it's short and consists entirely of repeated characters (e.g., cc) we're not going to gain much at all. At the same time, if the needle is short, the \$O(MN)\$ method is already close to the \$O(N)\$ we'd like. It's only when \$M\$ is large that the \$O(MN)\$ method becomes a serious problem--and that's exactly when a Boyer-Moore (or variant) search is most likely to give us the biggest gain (the primary exception being when/if the needle is long, but contains lots of repetition). Since big-O deals with the worst case, I think this is still \$O(MN)\$--but that only arises if the needle consists entirely of repetitions of a single character, and the haystack consists almost entirely of that same character as well. That's  fairly degenerate (and probably unusual case, but to use @Coderodde's example, if you're searching for cc in cccc, all the work is mostly wasted, because you're going to do a full comparison at every candidate position in the haystack, so it still ends up as \$O(MN)\$.

Your code

Looking at your code, I'm most puzzled by your use of the found buffer. You're basically copying characters from the input to found as long as the two match, then checking the length of found to see if you've gotten a match.

Instead of that, I think I'd move the check for a match at the current position into a separate function, which would implement an algorithm on this general order:

for pos = 0 to needle.length()
    if (hay_stack[start_pos + pos] != needle[pos])
        return false
return true


I figured a much nicer way to deal with this.  Break it down into the repeatable elements, i.e. Addressing Mode and Operation then code them all separately and immutably, combining them in the right way to get all OpCodes.  Effectively doing functional programming in Java.

First: If you represent an operation, say ASL(arithmatic shift left) as an Enum (Operation), which has a parameter that is a lamba of a @FunctionalInterface (in this case called AddressedValueInstruction) and accepts two bytes and returns a result.
 (Note: RoxByte is just my custom implementation of a byte)

public enum Operation implements AddressedValueInstruction {
/** Shift all bits in byte left by one place, setting flags based on the result */
    ASL((a,r,m,v) -> {
        final RoxByte newValue = a.asl(v);
        r.setFlagsBasedOn(newValue);
        return newValue;
    }),

    ...

    @Override
    public RoxByte perform(Mos6502Alu alu, Registers registers, Memory memory, RoxByte value) {
        return instruction.perform(alu, registers, memory, value);
    }

Second: If you represent the Addressing Mode as an Enum then -similar to Operation- have one of the Enum parameters as a @FunctionalInterface (called Addressable) lambda you can say MyEnum.address(AddressedValueInstruction) which will address a value, then sent it to the given operation then address the result.

public enum AddressingMode implements Addressable {
    /** Expects no argument, operation will be performed using the Accumulator Register*/
    ACCUMULATOR("Accumulator", 1, (r, m, a, i) -> {
        final RoxByte value = r.getRegister(Registers.Register.ACCUMULATOR);
        r.setRegister(Registers.Register.ACCUMULATOR, i.perform(a, r, m, value));
    }),

    ...

    @Override
    public void address(Registers r, Memory m, Mos6502Alu alu, AddressedValueInstruction instruction) {
        address.address(r, m, alu, instruction);
    }

Third: This means you can create opcodes in the same way by creating combinations of addressing modes and operations with no specific code required, i.e. ASL_ACCUMULATOR(ACCUMULATOR, ASL) and it can be run with ASL_ACCUMULATOR.perform()

public enum OpCode implements Mos6502Instruction {
    ASL_A(0x0A, ACCUMULATOR, ASL),
    ...

    @Override
    public void perform(Mos6502Alu alu, Registers registers, Memory memory) {
        addressingMode.address(registers, memory, alu, operation::perform);
    }

This approach has the benefits of a class per opcode approach, without all the boiler plate.


@property (retain) id chessdelegate;

There are several things wrong with this line.

retain - While this technically still is a property attribute, it has been replaced by strong.  It does the exact same thing as strong, but strong is the vastly preferred term here.
retain or strong are both wrong here anyway.  Any delegate property should ALWAYS be weak or assign (and weak is better).  In almost every instance, the object server as a delegate already has a strong reference to the object with the delegate property.  If we create a strong reference back, we're creating a retain cycle and the memory will never be able to be deallocated.
id works as the type, technically, but we don't want to use that.  What we actually want is something that conforms to the protocol we've outlined.  We need to either forward declare the protocol, or probably better, just move the entire protocol definition before the class interface, and then change that type to id<ChessboardViewDelegate>.
chessdelegate - First, just delegate is more than fine.  Since we've changed the type to id<ChessboardViewDelegate>, we know what kind of delegate it is... the only reason to give the property a name more descriptive than just delegate is if the class has and needs more than one type of delegate.  AND, if you find yourself in this situation, please don't forget to camelcase the property.  But in the end, it should just be delegate.

So, here's what the line should actually look line:

@property (weak) id<ChessboardViewDelegate> delegate;

mouseDown, mouseUp, and click.  We're developing an iOS project, not OSX, right?  All iOS devices are touch devices.  Moreover, look at the UIView method you override: touchesBegan:withEvent:.  There is mouse in iOS and our method names should reflect that.

Now then, as for the actual meat of this review and your code, what are we actually looking at?

This is a UI element meant to represent a chessboard.  Apple is quite consistent with the Foundation classes in Cocoa Touch.  Classes, even unrelated classes, will have similarly named methods that provide similar functionality when it makes sense to do so.

Let's consider UITableView and UICollectionView for a moment (and I'm choosing these for a reason).  Look at the similarities between these objects--specifically, how their delegate/datasource methods work.

What does the actual view itself actually do?  It only does two things.  First, it asks its datasource for what it should draw at a particular index path (and then it takes care of displaying it).  Second, it receives the touch events, then calls a method on its delegate to give it an opportunity to respond to the touch event.

Remember when I said that we should rename the delegate to simply delegate and that the only reason it should be different is if you have multiple?  Well, it seems that in keeping with Apple's design for this sort of stuff, it makes sense that we would have both a delegate protocol and a datasource protocol, and as such, we should have a property for each:

@property (weak) id<ChessboardViewDelegate> delegate;
@property (weak) id<ChessboardviewDatasource> datasource;

Now, we the chessboard view detects a touch event, it lets the delegate know and give the delegate a chance to respond to this event.  Meanwhile, the chessboard should have a public method called reloadData (exactly as UITableView and UICollectionView have).  When this method is called, the chessboard view goes through a series of calls to its datasource to determine what to draw at each square.

The chessboard view itself can maintain some information like background image, background colors, how to draw the squares, borders, etc., and it can even have information for what a knight looks like or what a pawn or king, etc looks like, but it should call to a datasource to say "What occupies this square?" 64 times.  And with this in mind, it shouldn't even care about any of the chess rules.  If I want to put 64 black kings on the board, the chessboard view should be fine with it.

So here's how the program flow should work with this setup:

First, we load the chessboard.  Next, we "reload" data, this is the first time we call to the datasource.  We ask the datasource what the board position should look like.  This first call might be a new game of chess, or perhaps loading a chess puzzle, or loading a previously saved game.
Next, we wait for user input.  Once we have some user input, we call out to the delegate.  The delegate performs some logic.  Is this a valid move or not?  Do we need to calculate the AI's response to this move?  Anyway, the delegate is informed of the move that's attempting to be made.
Once we've determined the result of the attempted move, we update the data model, and we ask the chessboard view to reload.  We the view reloads via calling out to the datasource, which has updated data, so the board will be drawn differently, and we're back to step two of waiting for user input.  Step 2 and 3 repeat in a cycle until the logic in step 3 dictates that one player or the other has won.

What would make sense to accompany this class is an enum that accounts for all the possible square states.  Each square is limited to only a dozen-ish possible states:

typedef NS_ENUM(NSInteger, ChessboardViewSquareState) {
    ChessboardViewSquareStateUnoccupied,
    ChessboardViewSquareStateWhitePawn,
    ChessboardViewSquareStateWhiteRook,
    ChessboardViewSquareStateWhiteKnight,
    ChessboardViewSquareStateWhiteBishop,
    ChessboardViewSquareStateWhiteQueen,
    ChessboardViewSquareStateWhiteKing,
    ChessboardViewSquareStateBlackPawn,
    ChessboardViewSquareStateBlackRook,
    ChessboardViewSquareStateBlackKnight,
    ChessboardViewSquareStateBlackBishop,
    ChessboardViewSquareStateBlackQueen,
    ChessboardViewSquareStateBlackKing
}

Now, your datasource has a method that asks for one of these values:

@required - (ChessboardViewSquareState)chessboardView:(ChessboardView *)chessboardView stateForSquare:(ChessboardSquare)square;

The chessboard view calls this method on the datasource.  It tells the datasource which chessboard is asking for the square state and what square it's asking about.  The datasource simply returns a value from the above enum.

Notice the similarity between this method and UITableView's datasource method:

@required - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath)indexPath;

Oh, and the ChessboardSquare data type I mentioned?  This could be an enum with 64 different values, but what I think is actually better is a struct of two enums.

typedef NS_ENUM(NSInteger ChessboardRow) {
    ChessboardRow1,
    ChessboardRow2,
    // etc... to 8

typedef NS_ENUM(NSInteger ChessboardColumn) {
    ChessboardColumnA,
    ChessboardColumnB,
    // etc...

typedef struct {
    ChessboardRow row;
    ChessboardColumn column;
} ChessboardSquare;

I think it would be very beneficial to spend a lot of time studying the delegate/protocol pattern and write some unrelated practice projects dealing with UITableView and UICollectionView and really completely understanding how these ui elements interact with the data model and controllers behind them.

If I were writing this chessboard view, it'd be a UIView subclass, yes, but the view would have an 8x8 UICollectionView on it to serve as the chessboard.  It'd be the delegate and datasource to the collection view.  Now, when the collection view calls a delegate/datasource method on the ChessboardView, some of them the chessboard view can handle entirely on its own.  The rest it can handle mostly on its own, but it's going to call out to the Chessboard delegate/datasource to get the rest of the information concerning how it needs to display the board based on the current game state.


Decorator to cache a function result for some time

Rather than using *args you can supply a default positional only argument.

def temporary_cache(fn=None, *, ttl=60):
    ...
    if fn is not None:
        return decorator(fn)
    return decorator

If you feel following "flat is better than nested" is best, we can use functools.partial to remove the need to define decorator.

def temporary_cache(fn=None, *, ttl=60):
    if fn is None:
        return functools.partial(temporary_cache, ttl=ttl)

    @functools.wraps(fn)
    def inner(*args, **kwargs):
    ...

  for debugging, disable in production

You can use logging for this. I will leave actually implementing this as an exercise.

  I also couldn't abstain from using the new walrus operator (Python 3.8+), since I'm always looking for opportunities to use it in order to get a better feel for it.

A very reasonable thing to do. Abuse the new feature until you know what not to do. +1

However, I don't think this is a good place for it.
Given all the brackets in such a small space I'm getting bracket blindness.
I can't tell where one bracket ends and the others starts.
I am not a fan of func.cache = ... and func.cache_time. You can stop assigning to a function by using nonlocal.

Bringing this all together, and following some of my personal style guide, gets the following. I'm not really sure which is better, but it's food for thought.

from datetime import datetime
import functools

def temporary_cache(fn=None, *, ttl=60):
    if fn is None:
        return functools.partial(temporary_cache, ttl=ttl)

    cache = None
    cache_time = datetime.fromordinal(1)

    @functools.wraps(fn)
    def inner(*args, **kwargs):
        nonlocal cache, cache_time
        now = datetime.now()
        if ttl < (now - cache_time).total_seconds():
            cache = fn(*args, **kwargs)
            cache_time = now
        elif DEBUG:
            # for debugging, disable in production
            print("Cached", fn.__name__)
        return cache
    return inner


Repetitions

All your elif share the same structure. You just need to ensure that the inserted pattern is always 3 wide and you can drop your offsets adjustments. The logical next step is to use a dictionary to store the pattern and the row for each attempt:

_GOWN_MODIFIER = {
    1: (' O ', 2),
    2: (' | ', 3),
    3: ('/| ', 3),
    4: ('/|\\', 3),
    5: ('/  ', 4),
    6: ('/ \\', 4),
}

def wrong_answer(gown, attempt=0):

    height, width = len(gown), len(gown[-1].strip())

    offset1 = int((-width+23)*0.5)+1
    offset3 = int(ceil(0.5*(width-7)))
    if not attempt:
        return gown

    try:
        pattern, row = _GOWN_MODIFIER[attempt]
    except KeyError:
        raise Exception("Ops! The number of attempts must be an integer from 0 to 6.")
    else:
        gown[row] = '{:>{}s} {:>{}s}'.format(pattern, offset1, '|', offset3)

    return gown

Calculus

You do not need ceil nor int to perform an integer division by 2. In Python 2, / is already the operator you need. You can also use // which is also the same operation. The advantage of the latter over the former is that the behaviour is the same in Python 3, whereas / will perform a decimal division in Python 3.

_GOWN_MODIFIER = {
    1: (' O ', 2),
    2: (' | ', 3),
    3: ('/| ', 3),
    4: ('/|\\', 3),
    5: ('/  ', 4),
    6: ('/ \\', 4),
}

def wrong_answer(gown, attempt=0):
    if not attempt:
        return gown

    height, width = len(gown), len(gown[-1].strip())
    offset1 = (23 - width) // 2 + 1
    offset3 = (width - 6) // 2

    try:
        pattern, row = _GOWN_MODIFIER[attempt]
    except KeyError:
        raise Exception("Ops! The number of attempts must be an integer from 0 to 6.")
    else:
        gown[row] = '{:>{}s} {:>{}s}'.format(pattern, offset1, '|', offset3)

    return gown

def create_gown(width, height):
    half_width = width // 2
    gown = []
    gown.append('{:>{}s}'.format('_'*half_width, 10))
    gown.append('{:>{}s} {:>{}s}'.format(
        '|', 11 - half_width, '|', half_width-2))
    for i in range(height-3):
        gown.append('{:^{}s}'.format('|', 20))
    gown.append('{:^{}s}'.format('-'*width, 20))
    return gown

Creation vs modifications

You're aware that you can create sequences of repeating elements using seq(element) * count. You can use that to create your gown variable by repeating the pole and then modifying the top two rows and the last one; it should be more memory friendly as the space needed to store the list will be allocated in one go:

def create_gown(width, height):
    half_width = width // 2
    gown = ['{:^{}s}'.format('|', 20)] * height
    gown[0] = '{:>{}s}'.format('_' * half_width, 10)
    gown[1] = '{:>{}s} {:>{}s}'.format(
        '|', 11 - half_width, '|', half_width-2)
    gown[-1] = '{:^{}s}'.format('-' * width, 20)
    return gown

On modifying in place and returning a value

and a bit about printing too

Your wrong_answer both modifies the gown in place and return the modified value. This is unnecessary as the caller still should hold a reference to the value (which was modified). When calling the code, you can have:

gown2 = wrong_answer(gown, attempt=3)

but

>>> gown2 is gown
True

So there is really no point in duplicating references to the same object. Instead, what you can do is preprocess the printing job, so you don't really need the print_gown function:

def wrong_answer(gown, attempt=0):
    height, width = len(gown), len(gown[-1].strip())
    offset1 = (23 - width) // 2 + 1
    offset3 = (width - 6) // 2

    if attempt:
        try:
            pattern, row = _GOWN_MODIFIER[attempt]
        except KeyError:
            raise Exception("Ops! The number of attempts must be an integer from 0 to 6.")
        else:
            gown[row] = '{:>{}s} {:>{}s}'.format(pattern, offset1, '|', offset3)

    return '\n'.join(gown)

Usage:

print(wrong_answer(gown, attempt=3))

Exceptions

Raising a generic purpose Exception is bad practice, as it makes the except clauses trying to handle your code being able to catch more than they should. You should at least use a more generic exception (such as ValueError) or define your own:

class AlreadyHangedError(ValueError):
    pass

def wrong_answer(gown, attempt):
    ...
    raise AlreadyHangedError('...')
    ...

However, there is something odd in the way you use your wrong_answer: the caller is expected to call this function using increasing attempts. This is the job for a generator. By turning wrong_answer into a generator, you can call it to create a generator instance and then call next on this instance (or let a for loop do it for you) to get the next gown to print:

def wrong_answer(width, height):
    gown = create_gown(width, height)
    offset1 = (23 - width) // 2 + 1
    offset3 = (width - 6) // 2

    yield '\n'.join(gown)
    for attempt in range(1, 7):
        pattern, row = _GOWN_MODIFIER[attempt]
        gown[row] = '{:>{}s} {:>{}s}'.format(pattern, offset1, '|', offset3)
        yield '\n'.join(gown)

Usage:

for gown in wrong_answer(10, 7):
    print(gown)

or, in a more real-case scenario:

def hangman_game():
    for gown in wrong_answer(10, 7):
        while True:
            status = manage_user_input()
            if status == 'FAILED':  # Whatever
                break
            if status == 'COMPLETED':  # Whatever
                return
        print gown
    print 'You lose'

Magic numbers

create_gown seems to center the gown in 20-sized strings, but what if width is greater than that? At first, you should define this value and give it a meaningful name, and same for all values that derive from it; and then, you might want to take max(20, width) as a base for your calculus.


I suggest you use existing library functions, e.g. shutil.copyfileobj to do the copying. Edit to clarify, as Gareth said:  Use shutil.copyfileobj(chunk_file, temp_file) instead of temp_file.write(chunk_file.read()).

Other than that (allocating and reading into Python objects via chunk_file.read()) there's no obvious flaws with the code, but I/O in Python is to be avoided on that scale anyway.  I'd even say you could try using a shell script with cat $FILES > $OUTPUT and it could perform better.


Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters

Necessary imports are missing.
The prefix is discarded too aggressively. In a string abaacccc the entire abaa is discarded, and the result becomes 4 instead of 6.
Representing window as a StringBuilder seems excessive. A pair of indices into the original string is enough.


Your code can be much improved by adding a few data structures:

case class Point(x: Int, y: Int)
case class Interval(min: Int, max: Int)
case class Dimensions(horizontal: Interval, vertical: Interval)
case class Direction(relX: Int, relY: Int)

Further you should start to introduce functions everywhere you have a comment now, for instance:

def updateSearchSpace(space: Dimensions, pos: Position, dir: Direction): Dimensions

Since this is a function that receives Dimensions and returns Dimensions as well, it is an ideal candidate to make it a method of the Dimensions class.

In order to simplify the method it is helpful to add a convenience method to Interval first:

case class Interval(min: Int, max: Int) {
  def shrink(newBound: Int, dir: Int) = Interval(
    min = if (dir == 1) newBound else min,
    max = if (dir == -1) newBound else max
  )
}

This allows you to shrink Dimensions pretty elegantly.

case class Dimensions(horizontal: Interval, vertical: Interval) {
  def shrink(pos: Position, dir: Direction) = Dimensions(
    horizontal.shrink(pos.x, dir.relX),
    vertical.shrink(pos.y, dir.relY)
  )
}

Your new data structures also give you much nicer signatures for your methods in general.

def loop(x: Int, y: Int, minX: Int, minY: Int, maxX: Int, maxY: Int): Nothing

becomes

def loop(pos: Position, searchSpace: Dimensions): Nothing

Your function findNewRelativePositionOnAxis(...) looks like it wants to be a member of Interval. I'll leave this one for you as an exercise ;-)


If you're interested in learning OOP and don't have the ambition to work with embedded electronics (roughly everything smaller than a phone), you're really more interested in C++ than C. This review is written based on the assumption you want to write C++ and ignores C.

Your current method of reading a file is odd. While checking for EOF is a relatively easy method to check whether you've hit the end of a file yet, it's not the only thing you should check for when reading a file. C++ can check whether the input is still 'good'. You could do so like this:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

void readFile()
{
    std::ifstream input("file.txt", std::ios::in);
    std::string currentLine;
    std::vector<std::string> allLines;
    std::vector<std::string>::iterator itLines;
    while (input.good())
    {
        getline(input, currentLine);
        allLines.push_back(currentLine);
    }
    for (itLines = allLines.begin(); itLines != allLines.end(); itLines++)
    {
        // Iterate over the data you just read
    }

}

Note that since we don't return anything, a void will do.

Now you're reading all lines of data (up till every newline) and iterate over them, which appears to be what you want to do. Not only will this stop when the file has reached EOF, it will also check whether the stream hasn't failed or took a bad chunk somewhere along the way.


The from_string() function is missing a @staticmethod decorator, and thus does not work in Python 2.

Your greatest_common_divisor() function works using brute force: it literally tests every possible divisor and picks the greatest one that is common to both.  A much faster method is the Euclidean Algorithm.

@staticmethod
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

Validation and error handling could be tightened up a bit.

The rejection of floating-point arguments is inconsistent:

>>> Fraction(3.14, 1)
3.14/1
>>> Fraction.from_string('3.14/1')
Traceback (most recent call last):
  […]
  File "fraction.py", line 55, in <listcomp>
    return Fraction(*[int(i) for i in text.split('/')])
ValueError: invalid literal for int() with base 10: '3.14'

Instantiating a Fraction with strings initially appears to work, but fails in an odd way later.  Either both of these statements should work, or both should fail.

>>> Fraction('1', '3')
1/3
>>> Fraction('1', '3') + Fraction('2', '3')
Traceback (most recent call last):
  […]
  File "fraction.py", line 32, in div
    return [i for i in range(1,n+1) if n % i == 0]
TypeError: Can't convert 'int' object to str implicitly

In Fraction.from_string(), the abstraction is slightly leaky.  I would prefer to see a ValueError instead of the following:

>>> Fraction.from_string('1/3/5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "fraction.py", line 55, in from_string
    return Fraction(*[int(i) for i in text.split('/')])
TypeError: __init__() takes 3 positional arguments but 4 were given

Personally, I would choose to raise a ZeroDivisionError if the denominator is 0.

>>> Fraction(1, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "fraction.py", line 13, in __init__
    raise ValueError("Denominator must not be zero.")
ValueError: Denominator must not be zero.


Reusable webdriver framework using SOLID design principles

I'm not really sure that there is any good argument having these static fields, especially when it comes to unit testing the WebDriver class.

public class WebDriver
{
    private static Dictionary... // this
    private static Dictionary... // this
    private static AppSetting... // this

    static WebDriver() // this
    {
        ...
    }

    ...
}

I would suggest you change those to private readonly fields instead.

and then we have this Initialize() method hanging out on it's own -- which means your code could not compile as is.

public class Foo // where is the class?
{
    public void Initialize()
    {
        if (WebDriver == null)
        {
            WebDriver = new WebDriver(new AppSettingsConfiguration())
                .GetWebDriver(BaseData.Browser);
        }
    }
}

I highly would not recommend passing around the AppSettingsConfiguration class, when it seems like the only time you use it is to pull a string value by calling _AppSettingsConfiguration.GetConfiguration("WebDriverFolderPath").

It would make more sense for you to handle reading your configuration somewhere else and not make the WebDriver responsible for handling that... (This actually breaks your "S" in the SOLID principle).

I would probably advise to consider refactoring it along these lines...

public enum Browsers { Unknown, Ie, Chrome, Edge, FireFox }

public class WebDriverFactory
{
    private readonly string _path;

    public WebDriverFactory(string path)
    {
        if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));
        // also, consider to a check that the path exists

        _path = path;
    }

    public IWebDriver Construct(Browsers browser)
    {
        switch (browser)
        {
            case Browser.Edge:
            {
                var options = new EdgeOptions()
                {
                    PageLoadStrategy = PageLoadStrategy.Eager,
                    UseInPrivateBrowsing = true
                };
                return new EdgeDriver(_path, options, TimeSpan.FromSeconds(60));
            }
            case.Unknown:
                throw new Exception("not a valid browser");
            default:
                throw new NotImplementedException();
        }
    }
}


TypeScript Generics: Create a generic map

It took me a while to understand the way getItem() works in its current implementation. I even thought that there's a bug (after rereading the code, I see I was wrong about it).

Let's start with obvious. The ret variable; can be safely removed.
The whole search loop is counter-intuitive to me, because each element in the items array is an object which stores a value: T under a different key: string. If you really want to use items: object[], you'd rather have it's elements declared as { key: string, value: T }. And this immediately moves us to the next point that answers your question about the choice of the type of the backing object.
An entity that stores key-value pairs in TypeScript and JavaScript is Object. Why not use it instead? I don't know if using Object is disallowed by your real problem definition.

If it is not disallowed, it would be very natural to define items as an Object and wrap it into a GenericMap which exposes the API your problem requires.

However, if it is disallowed, you should not use it in the setItem()'s code (tmp[key] = item;) as well. Because it's technically same kind of a "cheat" anyway.

Below is the code that is built around an Object instead of an Array. As you can see, pretty much all of the operations are now "pass-through" one liners. Including the getItem() which you said got pretty long in the original code.

class GenericMap<T extends number | string> {
  private items: { [key: string]: T } = { };

  setItem(key: string, item: T): void {
    this.items[key] = item;
  }

  getItem(key: string): T {
    return this.items[key];
  }

  clear(): void {
    this.items = {};
  }

  printMap(): string {
    const itemsAsString = Object
      .getOwnPropertyNames(this.items)
      .map(key => `'${key}': ${this.getItem(key)}`)
      .join(", ");
    return `{ ${itemsAsString} }`;
  }
}

A few TypeScript style side notes:

private items: { [key: string]: T } = { };

If we initialize our fields in-place (as a part of their definition), we don't need an explicit constructor() which makes code shorter.
{ [key: string]: T } is a compiler hint that will -- at least in some cases -- help detecting incorrect usages of the field

I personally have never seen the whitespaces around < and > when used with generics, e.g. GenericMap < T extends number | string >. It's not TypeScript idiomatic I believe.

Hope, it helps.


Re-inventing the wheel: Binary search in Scala

You're doing a number of things that are very un-Scalaesque, chief among them:

mutable variables - using var instead of val
while loop - recursion is usually preferred
basic comparison operators can be used on strings - >, <, ==, etc.

There are also efficiency issues to be considered:

indexing into a List is slow - Vector and Array collections are better
mixed binary search - many implementations abandon the binary search and go into a straight linear search when the field of candidates becomes small enough.

With a few of these things in mind, here's an alternative approach. (A full binary search, just for simplicity.)

def checker(name: String, names: Seq[String]) : Boolean = {
  // sort the input once, use Array for fast indexing
  val arr: Array[String] = names.sorted.toArray

  // tail-recursive binary search for name in names
  def search(start: Int = 0, end: Int = arr.length -1): Boolean = {
    val mid = start + (end-start)/2
    if (start > end)           false                // can't be found
    else if (arr(mid) == name) true                 // found
    else if (arr(mid) > name)  search(start, mid-1) // narrow the field
    else                       search(mid+1, end)
  }
  search()  // do it
}

Result:

val lines = List("ally", "ben", "albert", "zong", "hermit", "??ennis", "123pat", "alfred", "zil", "zol", "zal")
checker("zong", lines)  // res0: Boolean = true
checker("zing", lines)  // res1: Boolean = false


What I'd like from you guys, is pretty much to judge the system, and maybe if someone will, post an estimate as to how hard this system would be to crack

For a professional cryptographer (which I am not), it would be very easy to crack, due to the following factors:

the system relies on rand (rand is not really safe for cryptographic code; consider using a mersene twister, like mt19937).
the algorithm has low entropy, meaning it is easy to brute-force it, using a password dictionary.
considering your decryption algorithm is deducing the key from the data itself, a hacker could do the same.

There are probably other factors making the code easy to crack, but as I said, I am not a crptographer.

  (given that the special characters will be random), and if there are more efficient ways to go about making this system more secure. (I might decided to encrypt usernames as well).

You are looking at a problem with a "yes/no" answer (i.e. you need to check that the data is the same, not use decrpyted data in more complex computations), you should consider a one-way hash.

The idea is to construct an ireversible function, (irreversible = "given x, f(x) is easy to compute, but given f(x) it is difficult/impossible to compute x").

Using a one-way function in your case:

To encode the password, you apply the function.

To check the password, you ask for user input, you apply the function on the input, then compare the result with the already computed value (the one you need to verify).

This will (theoretically) allow you to make an algorithm that is not required to be reversible for checking the data.

As a rule of thumb though, security code is notoriously hard to get right. Consider:

using third party solutions (like CryptoPP or OpenSSL)
using known solutions (OpenSSL, PGP/GPG)
implementing known cryptographic algorithms (look up symetric encryption, asymetric encryption, commercial hash functions and algorithms)


Project Euler 34 # Digit Factorials in Python

There is math.factorial function. So no need to reinvent it.
Using try/except for control flow is a bad practice. It's better to explicitly check whether a list contains a value using the condition if int(digit) in factorials. It also will eliminate the code duplication in except branch.
It's even better to pre-calculate all factorials for digits from 0 to 9. Anyway, you will reuse them all a lot of times.


Find element yielding the largest value w.r.t. custom function

Setting aside the std::accumulate discussion, I have one recommendation. The signature

template<typename Iterator, typename UnaryFun>
auto maxElementBy(Iterator first, Iterator last, UnaryFun criterion)
    -> Iterator

seems to be more flexible. It allows partial ranges, and seems more in line with the std design approach.


Parse data from Input file and print results

The code looks fine and it is working for the given input
data. However, it can be difficult to
assess which inputs will be regarded as valid, and how it will behave
in case of unexpected input. One approach to uncertainty about code
(will it work?) is to let it pass through a testing framework. This
requires splitting your code into smaller units that can easily be
tested.
At the end of this post, I will present an example of how the code can
be adapted to a testing framework, but before that there are some
minor issues I would like to mention.
Unecessary g and m flag
Consider this line:
if( $data[0] =~ /FileName=([^_]+(?=_))_(\S+)_file.csv:(\S+),/gm ){

Since the code is only processing a single line at a time and there is only one
node on each line, global matching is not necessary. Also the m is
not needed. It allows ^ and $ to match internal the start and end of
internal lines for a multiline string.
Unnecessary use of lookahead regex
Consider this line:
if( $data[0] =~ /FileName=([^_]+(?=_))_(\S+)_file.csv:(\S+),/gm ){

First, as commented above we can remove the g and m flags. Then
/[^_]+(?=_)_/

is simpler written as
/[^_]+_/

Make code easier to read
This code:
($node, $time, $unit) = ($2, $1, $3);

is easier to read (my opinion) if written as:
($time, $node, $unit) = ($1, $2, $3);

such that the capture variables are sorted in numerical order. Similar
for this line:
my ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);

it can be written as:
my ($year, $month, $day, $hour, $minute, $second ) = ( $1, $2, $3, $4, $5, 0);

Shebang
See this blog for more information.
I usually use #!/usr/bin/env perl instead of #!/usr/bin/perl.
Most systems have /usr/bin/env, and it allows your script to run if you e.g.have multiple perls on your system. For example if you are using perlbrew.
say vs print
I prefer to use say instead of print to avoid typing a final
newline character for print statements.
The say function was introduced in
perl 5.10, and is mad available by adding use v5.10 or use use feature qw(say) to the top of your script.
Declare variable as close to their definition as possible
By declaring variable in the same scope as they are used and as close
the their first usage point as possible will help a reader to quickly
reason about the code, which will help producing correct code. For example,
in this code
my ($second,$minute,$hour,$day,$month,$year);
if ($datetime =~ /(....)(..)(..)(..)(..)/){
    ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);

the variables are only used within the if clause, so we can write it as:
if ($datetime =~ /(....)(..)(..)(..)(..)/){
    my ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);

Easier parsing of dates using Time::Piece
In the program below, I show how you can use Time::Piece instead of
timelocal to simplify the parsing of dates.
Example code with unit tests
Main script p.pl:
 #! /usr/bin/env perl

package Main;
use feature qw(say);
use strict;
use warnings;

use Carp;
use Data::Dumper qw(Dumper);

# Written as a modulino: See Chapter 17 in "Mastering Perl". Executes main() if
#   run as script, otherwise, if the file is imported from the test scripts,
#   main() is not run.
main() unless caller;

sub main {
    my $self = Main->new();
    $self->run_program();
}

# ---------------------------------------------
# Methods and subroutines in alphabetical order
# ---------------------------------------------

sub bad_arguments { die "Bad arguments\n" }

sub init_process_line {
    my ( $self ) = @_;

    $self->{lineno} = 1;
}

sub new {
    my ( $class, %args ) = @_;

    my $self = bless \%args, $class;
}

sub process_line {
    my ($self, $line) = @_;

    my $proc = ProcessLine->new( $line, $self->{lineno} );
    $self->{lineno}++;
    return $proc->process();
}

sub read_data {
    my ( $self ) = @_;

    # TODO: Read the data from file instead!
    my $data = [
'Node=01:FileName=A20200804.1815+0530-1816+0530_Network=NODE01_file.csv:Unit=R1,Meter=1 Vol 19,12,17,20,23,15,16,11,13,17',
'Node=02:FileName=A20200804.1830+0530-1831+0530_Network=NODE02_file.csv:Unit=R5,Meter=3 Vol 12,13,15,16,10,15,15,13,14,11'
   ];

    $self->{data} = $data;
}

sub run_program {
    my ( $self ) = @_;
    $self->read_data();
    $self->init_process_line();
    for my $line ( @{$self->{data}} ) {
        my ($node, $dt, $unit, $val) = $self->process_line($line);
        my $res = {
            node => $node,
            dt   => $dt,
            unit => $unit,
            val  => $val,
        };
        # TODO: write the data to STDOUT or to file in correct format
        print Dumper($res);
    }
}

package ProcessLine;
use feature qw(say);
use strict;
use warnings;

use Carp;
use POSIX qw( strftime );
use Time::Piece;

sub convert_date_to_epoch {
    my ( $self,  $date ) = @_;

    my $unix_time = Time::Piece->strptime( $date, "%Y%m%d.%H%M%z" )->epoch();
    return $unix_time;
}

# INPUT:
#  - $time_piece : initialized Time::Piece object
#
#
sub convert_epoch_to_date {
    my ( $self,  $time_piece ) = @_;

    my $dt = $time_piece->strftime("%Y-%m-%d %H:%M:%S");

    return $dt;
}

sub get_volumes {
    my ( $self,  $data ) = @_;

    $self->parse_error("No volumes") if !defined $data;
    my @vols = split /,/, $data;
    $self->parse_error("No volumes") if @vols == 0;
    for my $vol ( @vols ) {
        if ( $vol !~ /^\d+$/ ) {
            $self->parse_error("Volume not positive integer");
        }
    }
    return \@vols;
}

# INPUT:
#  - $volumes : list of volumes (integers).
#
# RETURNS: - index of smallest item (if there are multiple minimal, the index of
#  the first is returned.
#
# ASSUMES:
#  - Length of list >= 1
#  - Each item is a positive integer.
#  - NOTE: The items do not need to be unique.
#
sub find_min_vol {
    my ( $self, $volumes) = @_;

    my $min = $volumes->[0];
    my $idx = 0;
    for my $i (1..$#$volumes) {
        my $value = $volumes->[$i];
        if ( $value < $min) {
            $min = $value;
            $idx = $i;
        }
    }
    return $idx;
}

sub new {
    my ( $class, $line, $lineno ) = @_;

    my $self = bless {line => $line, lineno => $lineno}, $class;
}

sub parse_error {
    my ( $self, $msg ) = @_;

    croak ( sprintf( "Line %d: %s : '%s'\n", $self->{lineno}, $msg,
                 $self->{line} // "[undef]" ) );
}

sub process {
    my ($self) = @_;

    my $line = $self->{line};
    chomp $line;
    $self->parse_error("Empty line") if !$line;

    my ($field1, $field3) = $self->split_line( $line );
    my $date = $field1->get_date();
    my $node = $field1->get_node();
    my $unit = $field1->get_unit();
    my $unix_time = $self->convert_date_to_epoch( $date );
    my $volumes = $self->get_volumes( $field3 );
    my $idx = $self->find_min_vol($volumes);
    my $vol = $volumes->[$idx];
    my $vol_epoch = $unix_time + $idx*6;
    my $time_piece = localtime($vol_epoch);  # convert to local time zone
    my $dt = $self->convert_epoch_to_date( $time_piece );
    return ($node, $dt, $unit, $vol);
}

# INPUT:
#  - $line: defined string
#
sub split_line {
    my ( $self, $line ) = @_;

    my @data = split / /, $line;
    my $N = scalar @data;
    $self->parse_error( "Expected 3 fields (space-separated). Got $N fields.") if $N !=3;
    return (Field0->new($self, $data[0]), $data[2]);
}

package Field0;
use feature qw(say);
use strict;
use warnings;

sub get_date {
    my ( $self ) = @_;
    my $data = $self->{data};
    my $date;
    if( $data =~ s/FileName=([^_]+)_// ) {
        my $time = $1;
        if( $time =~ /[a-zA-Z](\d{8}\.\d{4}[+-]\d{4})-\d{4}[+-]/ ) {
            $date = $1;
        }
        else {
            $self->{parent}->parse_error("Could not parse time info");
        }
    }
    else {
        $self->{parent}->parse_error("Could not parse time info");
    }
    $self->{data} = $data;
    return $date;
}

sub get_node {
    my ( $self ) = @_;
    my $data = $self->{data};
    my $node;
    if( $data =~ s/(\S+)_// ) {
        $node = $1;
    }
    else {
        $self->{parent}->parse_error("Could not parse node info");
    }
    $self->{data} = $data;
    return $node;
}

sub get_unit {
    my ( $self ) = @_;
    my $data = $self->{data};
    my $unit;
    if( $data =~ s/file\.csv:(\S+),// ) {
        $unit = $1;
    }
    else {
        $self->{parent}->parse_error("Could not parse unit info");
    }
    $self->{data} = $data;
    return $unit;
}

sub new {
    my ( $class, $parent, $data ) = @_;
    return bless {parent => $parent, data => $data}, $class;
}

Unit test script t/main.t:
use strict;
use warnings;
use Test2::Tools::Basic qw(diag done_testing note ok);
use Test2::Tools::Compare qw(is like);
use Test2::Tools::Exception qw(dies lives);
use Test2::Tools::Subtest qw(subtest_buffered);
use lib '.';
require "p.pl";

{
    subtest_buffered "split line" => \&split_line;
    subtest_buffered "get_date" => \&get_date;
    subtest_buffered "get_node" => \&get_node;
    # TODO: Complete the test suite..
    done_testing;
}

sub get_date {
    my $proc = ProcessLine->new( "", 1 );
    my $fld = Field0->new($proc, "Node=01:FileName=A20200804.1815+0530-1816+0530_N");
    is($fld->get_date(), '20200804.1815+0530', 'correct');
    $fld = Field0->new($proc, "ileName=A20200804.1815+0530-1816+0530_N");
    like(dies { $fld->get_date() }, qr/Could not parse/, "bad input");
    $fld = Field0->new($proc, "FileName=A20200804.1815-1816+0530_N");
    like(dies { $fld->get_date() }, qr/Could not parse/, "bad input2");
}

sub get_node {
    my $proc = ProcessLine->new( "", 1 );
    my $fld = Field0->new($proc, "Node=01:FileName=A20200804.1815+0530-1816+0530_N");
    # TODO: complete this sub test..
}

sub split_line {
    my $proc = ProcessLine->new( "", 1 );
    like(dies { $proc->split_line( "" ) }, qr/Got 0 fields/, "zero fields");
    like(dies { $proc->split_line( " " ) }, qr/Got 0 fields/, "zero fields");
    like(dies { $proc->split_line( "1" ) }, qr/Got 1 fields/, "one field");
    like(dies { $proc->split_line( "1 2" ) }, qr/Got 2 fields/, "two fields");
    my ($f1, $f3);
    ok(lives { ($f1, $f3) = $proc->split_line( "1 2 3" ) }, "three fields");
    is($f1->{data}, "1", "correct value");
    is($f3, "3", "correct value");
}


Finding the number of integers that are a square and a cube at the same time

Let's say a = 1, b = 1,000,000. Your code is a nested loop, each loop iterating a million times, for a total of one trillion tests. And I tell, out of my head, that the result is 10 and the numbers are 1, 2^6, 3^6, 4^6, 5^6, 6^6, 7^6, 8^6, 9^6 and 10^6.

The numbers that are both 2nd and 3rd powers are exactly the sixth powers of integers. So you can just iterate for i = 0, 1, 2, 3 etc., calculate j = i^6, then if j >= a and j <= b increase the counter, and if j > b then exit the loop. The time needed is proportional to the sixth root of b.

Even faster, if b was extremely large, calculate A = sixth root of a, round up to the nearest integer, and B = sixth root of b, rounded down to the nearest integer. The numbers from a to b that are sixth powers are exactly the sixth powers of the numbers from A to B, and there are B - A + 1 of them.


Computing divisibility and multiplication

Review

  see if I use the global variables, nested loops and two functions with parameters correctly

loopCount is a magic variable, its meaning beats me. Is it some kind of debugging assistant?
The indentations seem random picks between 4 and 8 spaces. Stick to 4.
The div method is public, the mul private. Why introduce this inconsistency?
Give full names to your methods for readabiliy divide, multiply.
The methods are void, printing the results to the console. This limits usability to zero. Separate interaction with the console from the method flow. Use return values to yield results. Let main log these results to the console.
As suggested in the comments, you can optimize division by probing the smallest prime divisor to minimize cycles in the loops.
Be a bit more consistent in aligning brackets with method declarations.
For readability and consistency, add a blank line after the imports and remove that blank line after the last method.


Why does my function think that "uiouioiu"is a plaindrome?

The reason it doesn't work is that "It is not" is converted into True, so when you analyze
"uiouioiu" the process eventually has to check the middle part "ui", the problem is that the answer "It is not" is then interpreted as True.

The same behaviour should also be obtained when testing the word "abca"


Searching within multiple objects of the bucket

A few remarks to add to @JoeWallis already excellent answer:

If you want speed, consider using the module cStringIO instead of StringIO. Since we are missing your import statements, I can't tell whether you have a try .. catch to conditionally import it or not. You should really post the whole code.
There are very few occasions when you want to keep commented out code. Generally speaking, the best thing to do is to remove dead code and let source control software remind you of what the old code was like.
Instead of zip, consider using itertools.izip which uses lazy evaluation to zip the iterables. In your case, it does not change many things since you never break early (in case of error maybe?) but in general, it saves more memory and sometimes avoids computing unused values.
You don't need the parenthesis in class storage():, unless you explicitly inherit from a class. Since you don't inherit from anything, you can simply drop them so that your code looks cleaner.


User input for student grades is too verbose

You should move most of the logic out of the main() function and into its own function or functions.  But perhaps you're not there yet in your class.

Similarly, using namespace std is not recommended.  See here.  Obviously this won't matter in this program, but it's a bad habit that you may want to avoid starting.

double grade1,grade2,grade3,grade4,grade5,grade6;

Whenever I see something like this, I want to rewrite it as an array:

const int NUMBER_OF_GRADES = 6;
double grades[NUMBER_OF_GRADES];

Personally, I'd also put the grade weights into their own array, but that's up to you.  You could also use a switch statement or an if/else if construct to handle the grade weights.

If you use a for loop to iterate over the entries of the array and calculate the totalGrade incrementally in each iteration over the loop, I think that you will be able to see how to use a single grade variable to replace the entries of the array.  If your class hasn't done for loops yet, you can get the same effect by ordering all uses of grade[0] or grade1 before you do anything with grade[1] or grade2.  This means that you will have to replace

totalGrade = grade1 + grade2 + grade3 + grade4 + grade5 + grade6;

with six separate statements that have the same effect.

As a matter of policy, you should probably do more error checking when you do a cin.  If you look around this site, you should be able to find several examples of people using while loops with error checking.

When I've seen people put the } and else on separate lines, they've always been in the same column.  Like this:

if (totalGrade < 9) {
    cout << "grade is: >> " << totalGrade << endl << endl;
    cout << "you have reproved  "<< endl;
}
else if (totalGrade < 9.5) {
    // the else makes this implicitly greater than or equal to 9
    cout << "grade is >> " << totalGrade << endl << endl;
    cout << "you have approved -" << endl;
}
else if (totalGrade <= 10) {
    // the else makes this implicitly greater than or equal to 9.5
    cout << "grade is: >> " << totalGrade << endl << endl;
    cout << "you have approved + " << endl;
}

I personally put them on the same line.  Putting them on separate lines leads to people separating them, which can lead to confusion.

Note that I changed the order.  This makes no functional difference, but it reduces the number of comparisons that you need to do.  Also, I'm not sure that you have to check that totalGrade <= 10.  A simple else might be enough for the last one.

You might want to think about why I changed <= 9.5 to < 9.5.  Hint:  I had to do that to keep the effect the same after I changed the order.

cout << "hi please enter the six grades ";
     << endl << endl;

This looks horribly wrong.  It may work but it is fragile.  Either remove the ; from the first line or add a cout to the beginning of the second line.


Best syntax for executing an action between each loop iteration.

The closest I've come to this in C or C++ is a slight modification to Knuth's loop-and-a-half:

template<class T>
void print(std::vector<T> const &x) {
  std::cout << '[';
  typename std::vector<T>::const_iterator
    begin = x.begin(),
    end = x.end();
  if (begin != end) {  // Duplicated condition to handle the empty case.
    while (true) {  // Here is the "loop and a half".
      std::cout << *begin;
      if (++begin == end) break;
      std::cout << ", ";
    }
  }
  std::cout << "]\n";
}

C++0x allows you to generalize:

template<class Iter, class Body, class Between>
void foreach(Iter begin, Iter end, Body body, Between between) {
  if (begin != end) {  // This duplication doesn't matter as it is
                       // wrapped up in a library function.
    while (true) {
      body(*begin);
      if (++begin == end) break;
      between();
    }
  }
}

template<class T>
void print(std::vector<T> const &x) {
  std::cout << '[';
  foreach(x.begin(), x.end(),
    [](T const& v) {
      std::cout << v;
      // Long code here is still readable.
    },
    []{
      std::cout << ", ";
      // Long code here is still readable.
    });
  std::cout << "]\n";
}

Lambda capture even allows you to modify local variables in the function calling foreach.


Adding input strings and finding occurrences of certain prefixes

Let us just assume for simplicity that the upper bound for word length is some constant, so we can do some string operations on words, like checking if string a is prefix of b in constant time (i.e. \$O(1)\$). We will have N queries in total.

Naive solution

if (a == "add")
{
    v.push_back(b);
}
else if (a == "find")
{
    ...
    for (string word : v)
        if (is_prefix(prefix, word))
            mycount++;
    ...
}

Let us calculate time complexity for the worst case.

add operation: \$O(1)\$*

find operation: O(N) (assuming there are already N words added, we need to check each of them if it starts with prefix)

In total: \$N * (O(1) + O(N)) = O(N^2)\$

Your solution

add operation: \$O(N log N)\$ (for sorting)

find operation: \$O(N)\$ (even though we stop the search after the last matching word, it does not help in worst case, in which we have to check all the words)

In total: \$O(N^2 log N)\$

Even though the complexity seems to get worse, you are on the right track!

Possible improvement

Let K be the largest possible number of words find operation could find.
We can modify the solution to iterate only through words that start with prefix (K words at most). Because the vector is kept sorted, with binary search, that has \$O(log N)\$ complexity, we can find the first matching word without iterating through all the words from the beginning. In C++ std::lower_bound can do that job for you.

find operation: \$O(log N) + O(K)\$

Now let us improve add operation. It turns out, if we just replace std::vector with std::set, that is always sorted and has pretty good insertion/deletion complexity. The complexity for find will not change but add will be faster.

add operation: \$O(log N)\$

In total: \$N * (O(log N) + O(K) + O(log N)) = O(N log N + N * K)\$

It would be an improvement if K was some small constant. But as I now see that we are not even asked to output those words but only number of words, from my experience I would say we should not assume that K is small. The solution is probably checked against worst-case scenario that should look like this:

add aaa1
add aaa2
add aaa3
... (continue N/2 times)
find aaa
find aaa
find aaa
... (continue N/2 times)

If each find iterates through all the words, we get \$O(N/2 * N/2) = O(N^2)\$. This is not good. That probably means that we cannot event iterate through all matching words during find operation.

Better solution

Use prefix tree. Again, assuming constant word length, inserts will be constant:

add operation: \$O(1)\$

We will be able to find a subtree for all matching words in constant time too. Now we need to count words that belong to that subtree. Iterating trough all the children would be too slow. We will modify our tree to make each node store number of children. That number will be equal to the number of words that start with the prefix. It is possible to modify add operation to keep that number updated without changing the complexity of add.

find operation: \$O(1)\$

In total: \$O(N)\$


List of all prime factors of a number, including repeats

Some general comments:

Hooray for docstrings! It’s great that you’re writing these – it makes your code much easier to read and review, because I know what it’s supposed to do (and so can judge whether it does it correctly). And in general, these are pretty good docstrings.

Do note that PEP 257 says that one-line docstrings should end in a period.
Don’t be stingy with variable names – characters are cheap, and if you write more descriptive names, the code becomes much easier to follow.

For example, in generate_primes(), known_primes is better than l.
There are a few minor PEP 8 violations – in particular, space after comma in function arguments (for i in range(1,n+1)) and a double-space before inline comments.
Use generators! Generators allow you to do lazy evaluation of large iterables (such as a list of prime numbers) – which can make a big difference for performance. If you’re not familiar with generators, they’re a really powerful tool in Python. I recommend Ned Batchelder’s PyCon talk.

Okay, now comments on the specific functions:

product() – no comments, looks fine.
generate_primes() – it’s a bit hard to follow, because of the short variable names. It might be helpful to have some logic explaining the motivation behind the different steps, although on inspection it appears to be mostly sound.

It does return 1 as a prime number. Convention usually dictates that 1 isn’t  a prime number – there might be a good reason to deviate from convention, but you should document it if so.

You could also hard-code 2 as the only even prime number, and then just check odd numbers after that – skip half the checks you have to do.

This is what a revised version of that function might look like, with better comments and variables names, and using generators:

def generate_primes(n):
    """Generates all the primes less than or equal to n."""
    if n == 1:
        return

    known_primes = [2]
    yield 2

    for i in range(3, n+1, 2):

        # Assume that i is prime until proven otherwise.
        is_prime = True

        for existing_prime in known_primes:

            # As i <= n, if i is coprime to all the primes <= sqrt(n),
            # it must be that i itself is prime.
            if existing_prime > math.sqrt(n):
                break

            # If i is a multiple of another prime number, then i itself
            # cannot be prime.
            if i % existing_prime == 0:
                is_prime = False
                break

        if is_prime:
            known_primes.append(i)
            yield i

prime_factor_set() – aside from the quirk with i != 1 to account for generate_primes(), this is fine. But let’s make it a lazy generator:

def prime_factors(n):
    """Generates the prime factors of n."""
    for prime in generate_primes(n):
        if n % prime == 0:
            yield prime

prime_factor_list() – I find the docstring and name a little confusing. It sounds like you’re returning a list of prime factors – in fact, what you have is the prime factorisation of n.

Your approach makes many calls into prime_factor_set, which in turn calls generate_primes. This is quite an expensive function, so you minimise the number of calls you require. In fact, you can get away with just 1. Get a list of all the prime factors of n, and then use them to chip away at n until they’re exhausted. Like so:

def prime_factorization(n):
    """Generates the prime factorization of n."""
    for factor in prime_factors(n):
        while n % factor == 0:
            yield factor
            n /= factor
        if n == 1:
            break

With our new generators-based approach, this is significantly faster than the original, because it only computes the prime factors of n as it requires them.


Just a few comments :

Your if (value == 0) and if (weight == 0) should probably be if (value <= 0) and if (weight <= 0).

Keep It Simple : because value and weight are final, you could probably make them public, removing the need for getters.

Also, you could make this an inner class/nested class if you don't plan to use it for anything else.

Purely personal but I'd rather avoid continue whenever it can be easily avoided. If your case, it's quite easy to put the whole block behind a if (item != 0 && weight != 0) (or even better : if (item > 0 && weight > 0)).

However, things could be even more straightforward : for (int item = 0; item <=items.length; item++) and for (int weight = 0;  weight <= maxWeight; weight++) could start at 1 because first iteration won't do anything anyway because condition if (item == 0 || weight == 0) will be true. Then, as far as I can tell, the guard is not needed anymore.


Automate html file editing with python - Change the author

I'm going to try writing a few different versions of your program. I think it would make for a nice, basic comparison of the various alternatives.
Of course, this all hinges on the number of changes, and their complexity, you wish to make. In that regard, it would be nice to get some more information on those changes, even if you haven't written the code for it yet.

Pure lxml, .find() with a simple XPath expression.
from lxml import etree

parser = etree.HTMLParser()
tree = etree.parse('../resources/author_parser_test_1.html', parser=parser)

author_tag = tree.find("./head/meta[@name='author']")

if author_tag is None:
    print("Couldn't find author tag")
else:
    author_tag.set('content', 'New Author')
    tree.write('../out/author_parser_test_1_res.html', method='html', pretty_print=False)

BeautifulSoup using lxml as the parser
from bs4 import BeautifulSoup

with open('../resources/author_parser_test_1.html', 'r') as file_1:
    soup = BeautifulSoup(file_1, features='lxml')

author_tag = soup.find('meta', attrs={'name': 'author'})

if author_tag is None:
    print("Couldn't find author tag")
else:
    author_tag['content'] = 'New author'
    with open('../out/author_parser_test_1_res.html', 'w') as file_1:
        file_1.write(soup.prettify())

I will keep updating this post as I work.


One suggestion, use

use warnings;

use strict;

Will force you to be a better perl programmer, by enforcing more rigidity to your scripts, and have the intepreter catch any nasty issues that might be otherwise hard to debug.


Show list of numbers 1-10 multiplied by user entered number

Couple of things I noticed about your code.

Nothing happens if you enter any of the numbers 3,4,5,6,7,8 due to the else if statement checking for below 2 or above 9 instead of anything other than 2 or 9. To resolve this you should use an else instead of an else if as it will catch anything that is not 2 or 9 which is caught in the if statement.
You have created a manual infinite loop in your else if, the for loop will keep looping as long as the user enters a number below 2 or above 9 this is dangerous, if the number is not matched then it should reset the user back to a prompt and back to first if statement in theory.

How does the below catch your fancy?

let value = prompt("Enter Value between 2 or 9");

let loopAndOutput = function(value){
  if(value == 2 || value == 9){
    for(let i = 0; i < 10; i++){
      console.log(`${i} times ${value} is:${value * i}`);
    }
  } else {
    let value = prompt("Enter Value between 2 or 9");
    loopAndOutput(value);
  }
}

loopAndOutput(value);


A sum of first \$n\$ numbers is \$\frac{n(n+1)}{2}\$. A sum of squares of first \$n\$ numbers is \$\frac{n(n+1)(2n+1)}{6}\$. A difference in question is \$\frac{n^2(n+1)^2}{4} - \frac{n(n+1)(2n+1)}{6} = \frac{(n-2)(n-1)n(n+1)}{12}\$.

This solution is likely the most efficient.


FizzBuzz in F# with functional programming

I think it all seems quite functional. So nothing to argue about there. I like your use of List.reduce (>>).

Instead of the use of the union type FBCase, I would use the tuples directly in a way like this (some of the functions then may need a renaming):

let makeFBCase num =
    (num, "")

let unpackFBCase (num, txt) =
    match txt with
    | "" -> num |> string
    | _ -> txt

// Instead of input I use the tuple (num, text) to make it possible to call the elements directly
let fbBuilder (denom, str) (num, txt) =
    match num % denom with
    | 0 -> (num, txt + str)
    | _ -> (num, txt)

let createFBPipeline inputList =
    inputList |> List.map fbBuilder |> List.reduce (>>)

let createFBPattern inputList =
    makeFBCase >> (inputList |> createFBPipeline) >> unpackFBCase

let fizzBuzz = createFBPattern [(3, "Fizz"); (5, "Buzz")]

let fizzBuzzBaz = createFBPattern [(3, "Fizz"); (5, "Buzz"); (7, "Baz")]

let fizzBuzzBazQuux = createFBPattern [(3, "Fizz"); (5, "Buzz"); (7, "Baz"); (11, "Quux")]

In this way I don't think you lose any clarity.

Although your efforts show a good understanding of details of functional programming, I think you make it all too complicated. The overall task is to map a list of integers to either the integer itself or a text in respect to one or more predicates. That can be done like this:

let fizzBuzz fizzBuzzes data =
    let checkFizzBuzzes value =
        let result = fizzBuzzes |> List.fold (fun acc (num, txt) -> if value % num = 0 then sprintf "%s%s" acc txt else acc) ""
        match result with
        | "" -> value |> string
        | _ -> result

    data |> List.map checkFizzBuzzes

let data = [1..30]
data |> fizzBuzz [ (3, "Fizz"); (5, "Buzz"); (7, "Baz"); (11, "Quux") ] |> List.iter (printf "%s ")


Your Node type should really be generic with Node<T>, so that you could easily store a Node<Integer>, Node<Double>, Node<BigInteger>, Node<String>, etc.

The function printTree accesses no external state. As such, I'd recommend it be made a static function:

public static void <T> printTree(Node<T> head) {

When I see Queue<Node>, I imagine a LIFO data structure. Priority queues are not LIFO, so if you really want a priority queue, I'd actually say PriorityQueue<Node> q1 = new PriorityQueue<Node>(); However, this is up to preference; in general, it is good form to use Queue<Node>.

On the other hand, you may be simply looking for a queue datatype. In that case, you want ArrayDeque<Node>.

q1.size() > 0

Replace that with !q1.isEmpty(). It reads better.

while (q2.size() > 0) {
    q1.add(q2.poll());
}
q2.clear();

What you are doing here is actually simply

q1.addAll(q2);
q2.clear();

Putting this all together:

public static void <T> printTree(Node<T> head) {
    if (head == null)
        return;
    Queue<Node<T>> q1 = new ArrayDeque<>(); // Type name can be left out here Java 7+
    Queue<Node<T>> q2 = new ArrayDeque<>();

    q1.add(head);

    do {
        while (!q1.isEmpty()) {
            Node<T> element = q1.poll();
            System.out.print(element.data + " ");

            if (element.left != null)
                q2.add(element.left);
            if (element.right != null)
                q2.add(element.right);
        }
        System.out.println();

        q1.addAll(q2);
        q2.clear();
    } while (!q1.isEmpty());
}

There are several options for improvements once you reach here. One is to create a separate Iterator<Node<T>> for your nodes, then just iterate over the iterator printing each node. But I'd also prefer this code:

public static void <T> printTree(Node<T> head) {
    if (head == null)
        return;
    Queue<Node<T>> q1 = new ArrayDeque<>(); // Type name can be left out here Java 7+
    Queue<Node<T>> q2 = new ArrayDeque<>();

    q1.add(head);

    // while loops are more common; there is no change in functionality, but may be easier to read.
    while (!q1.isEmpty()) {
        for (Node<T> element : q1) { // This is a for each loop
            System.out.print(element.data + " ");

            if (element.left != null)
                q2.add(element.left);
            if (element.right != null)
                q2.add(element.right);
        }
        System.out.println();

        q1 = q2; // garbage collection isn't *too* expensive, and we get more expressive this way.
        q2 = new ArrayDeque<>();
    }
}


Ultimately, you are looking to see if any character is not either '0' or '1'.  The moment you find such a character, you can break the loop immediately:

int isBitString = 1;
for(int i = 0; i < len2; i++) {
    if (str[i] != '0' && str[i] != '1') {
        isBitString = 0;
        break;
    }
}


The second version is undoubtedly better, more readable, even if you iterate multiple times over the data.

The problem is: both versions, specially the first, suffer from a common problem: imperative style ("do this, do that"). Are you familiar with the difference between imperative (focus on statements and state change) and functional programming (focus on expressions and immutable data)? it's easy, just try to code without in-place updates (no each, delete_if, bang! methods, ...) and you'll see that you'll end up writing less code, easier to test, to debug and to understand. You'll pay a bit of memory/speed performance, but it's usually worth it.

Now, using a functional approach and taking advantage of existing libraries (uri), that's what I'd write (some details may not be right, but you get the idea):

require 'uri'

def parse(data, filter_tags)
  items, nested_tags, nested_locations = JSON.parse(data).map do |item|
    location = URI.parse(item["l"]).host rescue "URL Parse error"
    tags = item["t"].map(&:strip) - filter_tags
    [item, tags, location]
  end.transpose

  [items, nested_tags.flatten(1).uniq.sort, nested_locations.flatten(1).uniq.sort]
end

More on functional programming with Ruby: http://code.google.com/p/tokland/wiki/RubyFunctionalProgramming


Multicolumn iterations with cucumber data tables in Ruby

For this you could use a Scenario Outline, and I personally, would split that function into two separate functions.

Try doing something like this:

Scenario Outline: cannot access certain paths as roles
  When I access "<path>" as "<role>"
  Then I should see an error

Examples:
 | path   | role  |
 | /path1 | user1 |
 | /path2 | user2 |
 | /path3 | user3 |
 | /path4 |       |

Scenario Outlines are used when you want to test the same fundamental thing, using different parameters, without clogging up your feature file with many Scenarios.

They always use an examples table, and will run through the examples table replacing the placeholders (which will always match the heading rows), with the content of each row (as with a usual table).

In my opinion, this is the best way to test what you are attempting to do.

EDIT

In light of the comments below, maybe this would be the best course of action:

Scenario Outline: cannot access various paths as role 1
  When I access "<path>" as "user1"
  Then I should see an error

Examples:
| path   |
| /path1 |
| /path2 |
| /path3 |
| /path4 |

Scenario Outline: cannot access various paths as role 2
  When I access "<path>" as "user2"
  Then I should see an error

Examples:
| path   |
| /path1 |
| /path2 |
| /path3 |
| /path4 |

Scenario Outline: cannot access various paths as role 3
  When I access "<path>" as "user3"
  Then I should see an error

Examples:
| path   |
| /path1 |
| /path2 |
| /path3 |
| /path4 |

It may be longer, but it is more human readable than perhaps the table would.


Function that takes an object and a query obj that tries to regexp matches its values

I have reviewed your code and I can make the following remarks:

FP concepts

I understand that you want to solve the issue of matching objects to queries. If you pass an object and a query you should be able to check if the query satisfies all parts or no. However to be honest with you you try too much in the wrong direction. All that curryRight, flowRight, partial etc are very interesting and useful but in the average programmer they don't really mean anything for the problem you are trying to tackle.

For example I was able to rewrite the code using lodash chain in 5 minutes and with better readability. I will post my code at the end but before that I'll comment a few things:

matcher(obj, queryA): Why the name matcher? What does it matches? An object, an array? I think its too generic and confusing. And why does it accepts 2 parameters? Ideally it should accept only one at the time.It should have been like makeMatcher(obj) => (query) => ... and now you would have more flexibility with naming.

const matcher = curryRight(
  (state, query) =>
    flowRight([
      every(Boolean),
      map(
        (val, key) => {
          return  state[key] && state[key].match(new RegExp(val, 'ig'))
        }
      )
    ])(query)

This looks too esoteric and I had to search for the documentation for both flowRight and curryRight and after that I had to run your code to the browser with breakpoints to understand the internals etc. At some point I stopped because I thought it took me enough time already and its not worth it. Its clearly too complicated to read and to understand, not only now but also in 2 years time when you revisit your code and think what exactly did you meant to do. My point is that in the current state is un-maintainable.

Anyway here is my take on this:

const makeMatcher = (obj) => (query) => {
  const matchesQuery = (val, key) => {
    return obj[key] && obj[key].includes(query[key]);
  };

  return _(query)
          .chain()
          .map(matchesQuery)
          .every(Boolean)
          .value();
}

const objMatches = makeMatcher(obj);
objMatches(queryA); // True
objMatches(queryB); // False

Note how the code speaks of its self and it doesn't have to exaggerate. Every name has a meaning with the right intent. A makeMatcher makes matchers and an objMatches returns a boolean by accepting a query and checking if its matches the query.

Inside the makeMatcher we simply chain over the query and validate that either every query parameter matches the object or in case of a mismatch we return false and that's it.

My point is that you should always have a birds eye view of your code and try to think of ways to make your work easier to handle. Search for alternatives and don't fall into the rabbit hole of applying things that they don't fit accurately. There is always a simpler method to do your job. Good luck with your FP endeavors.


Split string by list of separators and return used separator in the correct order

The standard library offers strstr.
It seems more natural to look for separators in the string, rather for string characters in separators.
value and separators better be passed as const std::string& to make sure they are not attempted to be mutated.
Out parameters are typically frowned upon. Consider returning an std::pair<std::vector<string>, std::vector<char>>.


Scraping names from multipages without clicking on the next button

The code is pretty much straightforward and understandable, but I would still work on the following stylistic and readability issues:

extract constants. It might be a good idea to extract the URL template and maximum page number into separate constants, or as arguments of a function
put your main execution logic into the if __name__ == '__main__' to avoid it being executed if the module is imported
avoid using bare exception clauses. Be specific about the exceptions you are handling. In this case, NoSuchElementException is a good exception to handle if an item name is not found
use try/finally to safely close the driver if it fails before quitting - this way you would eliminate a situation when you have opened "ghost" browser windows left from failed scraping tries

All things applied:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def scrape(url, max_page_number):
    driver = webdriver.Chrome()
    wait = WebDriverWait(driver, 10)

    try:
        for page_number in range(1, max_page_number + 1):
            driver.get(url.format(page_number))

            for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".info"))):
                try:
                    name = item.find_element_by_css_selector('a.business-name span[itemprop=name]').text
                except NoSuchElementException:
                    name = ''

                print(name)
    finally:
        driver.quit()

if __name__ == '__main__':
    url_template = 'https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=San%20Francisco%2C%20CA&page={0}'
    max_page_number = 2

    scrape(url_template, max_page_number)


Javascript Stringify Nested Objects with Loop References

JSON.stringify() and JSON.parse() were meant to serialize and deserialize data. This is why it omits non-data (functions, regex, etc.) on purpose. When you mention serializing prototypes, you are serializing behavior and object relationships, not data. It's the same reason why JSON is preferred over XML for AJAX, because JSON is a data exchange format while XML is a document format.

I suggest you rethink your approach before this becomes a rabbit hole.

FWIW, JSON.serialize() accepts a replacer function as second arg, while JSON.parse() accepts a reviver function as second arg. If what you're building is some kind of object mapper, you can use the replacer to insert metadata about the constructor for that instance, and use the reviver to pick up that metadata and customize how that object instance is created.