I'll first suggest you that the raw format that you use to store your data, use a different separator than a white-space. This will simplify the code since we are sure that we have unique separator.

Your TreeEntry should encapsulate his fields in getter and setter. Public field in a class is not something that you want to do in a OOP program. You should always limit the scope of your variable. Your TreeEntry class should look like :

class TreeEntry {

    private String perms;
    private String type;
    private String hash;
    private String name;

    @Override
    public String toString() {
        return perms + " " + type + " " + hash + " " + name;
    }

    public String getPerms() {
        return perms;
    }

    public void setPerms(String perms) {
        this.perms = perms;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getHash() {
        return hash;
    }

    public void setHash(String hash) {
        this.hash = hash;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

For the parsing part, I will use a different format than yours. I use the ; character to separate each "column" of the data. The format would look like :

tree;503(null)040000;tree;0bfec80bc7b7aa0a50e0b373044929cb0aae278b;build/
100755;blob;e30876c61eb7712ad09b50593a30513d9b173805;build.xml
100755;blob;1574df4a2de5d2884f33a5d3e30ae3daa5affee1;manifest.mf
040000;tree;fdab6a12a56a709212f105c9c8e31cd062d01e0a;nbproject/

I've changed a lot of things in the parseTree() method so I'll drop the new method and I'll explain later what are the changes and why.

private static List<TreeEntry> parseTree(String hash) {
    String tree = readObject(hash);

    if (!tree.startsWith("tree")) {
        System.err.println("Given hash doesn't belong to a tree object");
        return null;
    }

    List<TreeEntry> entries = new LinkedList<>();

    // // We are interested in data after null character
    int nullCharacterPosition = tree.indexOf("\0");
    tree = tree.substring(nullCharacterPosition + 1);

    String[] dataTree = tree.split("\n");

    for (String entry : dataTree) {
        TreeEntry e = new TreeEntry();
        String[] args = entry.split(";");
        e.setPerms(args[0]);
        e.setType(args[1]);
        e.setHash(args[2]);
        e.setName(args[3]);
        entries.add(e);
    }

    return entries;
}

If you want to find the null character, you should use indexOf, this will do the loop for you and will return the index of the first character corresponding. Since I don't have an input with a null value, I've not tested my code to find the null character. So be sure to verify this part.

I've also changed the type of entries to a List. I've choose a LinkedList since all the operation I'm doing is adding new entries, and you'll probably iterate over it later. This allow to focus on the task of parsing and I don't have to manage the array (I don't have to check the size before adding something).

I've used the spilt() method instead of the StringTokenizer. I've find it easy to operate in conjunction with a for-each loop, and you don't seems to want to work with anything than String, so split() is perfect for that. I'll point you to this question for further information on why I would not use StringTokenizer, read the second answer.

It seems rather odds to me that the parsing method is static. I don't know where the method is called, but I would have go with something like a factory or utility class to do the parsing job.

PS: This is my first review, so if this is not a good format or there is some inaccuracy let me know.


Creating a slider to adjust the width and two click events

I was able to take out 5 lines worth after noticing that some lines weren't being used or used twice in the click events.

$("li").click(function(){
    $(".selector").css("visibility","hidden");
    var offSet = 7;
    if($(this).hasClass('Selected')){
        $(this).removeClass('Selected');
        $(this).css("box-shadow", "none");
        $(this).children("div").css("visibility","hidden");
    } else{
        $("li").css("box-shadow", "none");
        $(this).addClass('Selected').siblings().removeClass('Selected');
        $(this).css("box-shadow", "inset 0 0 " + offSet + "px #333");
        $(this).children("div").css("visibility","visible");
    }
});

$("#sideNav > ul > li").click(function(){
    var element = $("#content");
    var offsetElement = $("#subSideNav");
    var offSet = parseInt(offsetElement.css("width")) + 2;

    if($(this).attr('id') === "Selected" && !element.hasClass('large')){
        $(this).attr('id', '');
        slider(element, offSet, 'hidden');
        element.addClass('large');
    } else if($(this).attr('id') !== 'Selected' && element.hasClass('large')){
        offsetElement.css('display', 'block');
        $(this).attr('id', 'Selected');
        slider(element, offSet, 'visible');
        element.removeClass('large');
    } else if($(this).attr('id') !== 'Selected' && !element.hasClass('large')){
        $(this).attr('id', 'Selected').siblings().attr('id', '');
    }
});


Addition/Deletion records based on method argument

Performance wise you're not going to notice the difference.

There is a far better solution available to you though. That is to have 2 separate methods altogether.

You already have a switch statement before calling the method in which you know that it will be a delete or an add. This makes it really easy to just call the right method.

Having separate methods that each do a specific thing makes the code easier to read and maintain later on.


Computing the Kronecker product over a tensor chain

Assuming M is non-negative you can make it clear when J and R are returned and remove some of the nested if-else's.
Since if i+1 ==m only evaluates as true if m <= M you could check that and use different for loops if it's true/false to make things slightly faster but I think that would decrease readability for not much gain
def make_rotate_target(m, M, J, R):
    if M == 0:
        return J

    if M == 1:
        return R

    out = J
    for i in range(1, M):
        if i + 1 == m:
            out = np.kron(out, R)
        else:
            out = np.kron(out, J)

    return out


Do not use namespace std;
Put your code into functions if possible. For example the Question for the user should be a single function.

void printOptions() {
     std::cout << "Your choices of drinks are: " << "\n";
     std::cout << "1 - Coke" << "\n";
     std::cout << "2 - Sprite" << "\n";
     std::cout << "3 - Water" << "\n";
     std::cout << "4 - Orange Juice" << "\n";
     std::cout << "5 - Apple Juice" << "\n";
     std::cout << "What drink would you like (1/5): ";

}

Note that i use "\n" instead of std::endl as this doesnt flush the stream.
Use a dedicated input function

int chooseBeverage() {
    int beverage;
    std::cin >> beverage;
    return beverage;
}

Now define a function that takes the choice and give the beverage.

enum choice {
    NONE = 0;
    COKE,
    SPRITE,
    WATER,
    ORANGE_JUICE,
    APPLE_JUICE
};

void serveBeverageIf(choice beverage) {
     if(beverage == COKE)
        std::cout << "You chose Coke." << "\n";
     else if(beverage == SPRITE)
        std::cout << "You chose Sprite." << "\n";
     else if(beverage == WATER)
        std::cout << "You chose Water." << "\n";
     else if(beverage == ORANGE_JUICE)
        std::cout << "You chose Orange Juice." << "\n";
     else if(beverage == APPLE_JUICE)
        std::cout << "You chose Apple juice." << "\n";
     else
        std::cout << "Error. choice was not valid, here is your money back.";
 }

 void serveBeverageSwitch(choice beverage) {
     switch(beverage)
     case COKE:
        std::cout << "You chose Coke." << "\n";
        break;
     case SPRITE:
        std::cout << "You chose Sprite." << "\n";
        break;
     case WATER:
        std::cout << "You chose Water." << "\n";
        break;
     case ORANGE_JUICE:
        std::cout << "You chose Orange Juice." << "\n";
        break;
     case APPLE_JUICE:
        std::cout << "You chose Apple juice." << "\n";
        break;
     default:
        std::cout << "Error. choice was not valid, here is your money back.";
        break;
     }
 }

What you could also do is use a third option utilizing a map.

void serveBeverageMap(choice beverage) {
map<choice, std::string> nameMap = {
    std::make_pair(COKE, "Coke"),
    std::make_pair(SPRITE, "Sprite"),
    std::make_pair(WATER, "Water"),
    std::make_pair(ORANGE_JUICE, "Orange juice"),
    std::make_pair(APPLE_JUICE, "Apple juice")
};
if(nameMap.find(beverage) == nameMap.end()) {
   std::cout << "Error. choice was not valid, here is your money back.";
} else {
    std::cout << You chose " << nameMap[beverage] << ".";
}
}


There's a bug:

>>> a = [1, 2, 3]
>>> findsum(a, 0)
False

but the result should be True because the consecutive slice a[0:0] sums to zero.
The docstring could be clearer. "a consecutive array slice" — of which array? Presumably the parameter a is meant, but it is best to be explicit. Similarly, "Find whether" — and then what? The docstring should say what value is returned.
The function has runtime \$Θ(n^3)\$. That's because sum(a[i:j]) takes an unnecessary copy of the slice, and because it sums it starting at the beginning of the slice. But if you maintained a running sum, then the runtime would come down to \$Θ(n^2)\$. That's easy to implement using itertools.accumulate and  itertools.islice:

from itertools import accumulate, islice

def findsum(a, n):
    """Return True if any consecutive slice of the sequence a sums to n,
    False if none do.

    """
    return n == 0 or any(total == n
                         for i in range(len(a))
                         for total in accumulate(islice(a, i, None)))


Manipulating an ES6 static class property that is an array

Protected states require enforcement..
Why would you use the possible colors and complicated apple color vetting process when there is no requirement in your code to do so?
You are using a static list (array) in an effort to protect the state of the Apple, or associated states that rely on apples being specific colors.
Maintaining trust in object states is important and allows you to make assumptions and reduce the code complexity. It is also one of the most important methods coders have of controlling our arch nemeses.. The Bug!
But a chain is only as strong as its weakest link. Even if you put a big sign above it saying "Don't yank this pitifully weak link!" you can't trust coders, not even yourself, for one day the convenience is too tempting, and while in a rush to meet a dead line you yank that chain.
const myApple = new Apple();  // Needs to be "Reddish" not "red"
myApple._color = "Reddish";   // Done, so much easier than wrangling the
                              // possibleColors static and its dificult siblings

And just like that all the work put into protecting the state of your apple is out the window.
Coders are lazy they will not put up with complications if there is an easy way. Coders want performant code and they are not going to use getters and setters when there is direct access. Putting a sign up "Do not use" (_ as the metaphoric sign "private") does not stop use.
If you want to control the color of the apple you must make it impossible to change it without the vetting process, or it is pointless, and pointless code is bad code.


A few comments:
Exceptions:
Keep in mind, even with using-statements, exceptions can happen. Make sure to catch them. I'd suggest, you wrap the whole snippet in a try-catch-block if that didn't happen already.
Types:
Why are you using the dynamyic type? Make it easier for readers and yourself by using the correct type. For yourself? Yes, if you use the explicit type, you get way better IntelliSense  proposals.
Accessing:
reading a bit through the msdn documentation for OracleDataReader I found, that there is a property for the reader, named Item with 2 overloads. One being Item[String].
It seems they return the Column Value "in it's native format".
using (OracleDataReader reader = oracleCommand.ExecuteReader())
{
   while (reader.Read())
   {
      number = reader.Item["ID"];
      dateTime = reader.Item["Begin"];
   }
}

Update:
@Sandeep claims that the return type is in fact Object. If that is the case, you will have to run a conversion: number = Convert.ToInt32(reader.Item["ID"]);
Furthermore it seems that reader.Item[index] can actually be replaced by reader[index].


Finding overlapping time intervals for two games

Depends on what you want. Typically programming challenges are not validated on clean code. But on correctness and efficiency.

  Use libraries:

You are having a lot of duplicate code, parsing numbers. Check out the Scanner class which has these methods builtin.

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Remark: When efficiency is important, Scanner may be a lot slower than BufferedReader. In this case I still recommend putting the one time effort of creating your own custom read methods.

  Efficiency:

You are looping over all intervals. This means you have to check all intervals with each other. Hence complexity: O(N²)

This is a well known problem, you could find a lot of reading about this online if you want.

  General:

Write your overlap with less comparissons.

// overlaps when A starts before B ends AND B starts before A ends
private static boolean fight(int[] game1, int[] game2) {
    return game1[0] < game2[1] && game2[0] < game1[1];
}

For readability I would recommend create a class instead of working with int[2]. Typos are sometimes difficult to track.

class Game
{
    private int start;
    private int end;

    public Game(int start, int end)
    {
        this.start = start;
        this.end = end;
    }

    public bool overlaps(Game other)
    {
        return this.start < other.end && other.start < this.end;
    }
}


optimizing a bash script chain - speed suggestions?

It's not related, but please don't mind if I use an "answer" to just comment : it seems I can't comment, maybe because I don't have enough points yet to do so...

Tarrasch, if you still use csh for your shell, please do not script in it.

Please read: http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/

Use instead sh, bash (or even ksh). And better to stick to sh-only because that's what's all unix system rely on (and rc scripts, for example, are based on).


Spacing! Separate function definitions with blank lines.
I'd use a, b, c for type variables and x, y, z for variables.
A . looks cleaner than a $.
putStr . unlines . map show . fib $ read s :: Int

I would add another pair of parentheses to make the order of application absolutely obvious.
(l:ls) !: a = l : (ls !: a)

For similar reasons, I prefer the following.
fib n = fibBase ++ zipPoly (+) fibTails
    where fibBase = replicate (n-1) 0 ++ [1]
          fibTails = repFor tail (fib n) n

I'd use cs for the remainder of the list instead of c. Perhaps a where helps, too.
zipPoly f (a:b:cs) = zipPoly f $ c:cs
    where c = zipWith f a b

zipPoly needs the associativity of f, if I'm not mistaken. Perhaps its worth a comment.
Perhaps use a fold?
zipPoly f [] = []
zipPoly f (xs:xss) = foldl (zipWith f) xs xss

Don't reinvent the wheel too much :). Use Hoogle to search for a function using its signature.
For example, !: is snoc. Since you only use it once, I'd replace it with a ++. Similarly, repFor f x0 n is take n . iterate f $ x0.


Generic Makefile handling unit testing and folder structure

I'll assume throughout this answer that you're targeting GNU Make.  It's available on all targets that matter, and it simplifies your world no end if you can avoid pandering to the idiosyncrasies of the manifold implementations of Make supplied with operating systems.
Object files depend on headers
This is the biggest thing that I think could be improved; I think it's probably a whole question in itself.  Your object files naturally depend on the corresponding C++ source files, but they also need rebuilding when their headers change.  Consider including generated makefiles that tell make how the object files depend on the headers; for a suitable recipe, see the Stack Overflow question "Makefile, header dependencies", and for a longer exposition, read "Auto-Dependency Generation" by Paul D. Smith.  I normally use something like
-include $(OBJS:.o=.d)

%.d: %.c
    $(CC) $(CFLAGS) -MM -MT $@ -MF $@ $<

More warnings
It's good to see that you're using -Wall.  I also recommend
CXXFLAGS += -Wextra -Wwrite-strings -Wno-parentheses
CXXFLAGS += -Wpedantic -Warray-bounds -Weffc++

The first line above always helps; the second does sometimes improve my code (you'll want to make use of -isystem to quieten your library includes, if you want to  make the latter bearable).
Output directory
Rules of makefiles advises that

Life is simplest if the targets are built in the current working directory.
Use VPATH to locate the sources from the objects directory, not to locate the objects from the sources directory.

That's certainly something to consider, though it might already be too painful to change.  I certainly prefer out-of-tree builds, so I can clean up with rm -rf build/ and be left with just my sources.
Hiding commands
I appreciate that you don't want a wall of text, but when you're debugging (or on an automated build host where you want a complete record of the build), then you might want to override this, and actually see which commands were run.  You can make the behaviour adjustable, like this:
QUIET := @
ECHO := @echo
ifneq ($(QUIET),@)
ECHO := @true
endif

Use it for your commands:
clean clear:
    $(ECHO) "[CL]  out/"
    $(QUIET)$(RM) out/*
    $(ECHO) "[CL]  tmp/"
    $(QUIET)$(RM) tmp/*

I changed the order to print first, like Make does, according to the Principle of Least Surprise.  It makes it more obvious what action was in progress when any error occurs.
Now, when you need to see the actual commands, you can make QUIET= to override the value and get the full output again.  IIRC, the Linux kernel uses a similar system (toggled by a KConfig setting), as does Qt's qmake (toggled with CONFIG += silent in the .pro file).
Re-use Make's pre-defined commands
Instead of writing
%.o: %.cpp
    $(CXX) $(CXXFLAGS) -c $< $(INC) -o $@

%: $(OBJ)
    $(LD) $(LDFLAGS_TEST) $^ -o $@

you can make the rules more like the built-in versions (that you can see with make --print-database):
%.o: %.cpp
    $(COMPILE.cpp) $(OUTPUT_OPTION) $<

%: $(OBJ)
    $(LINK.cpp) $(OUTPUT_OPTION) $^ $(LOADLIBES) $(LDLIBS)

Adapted to use QUIET and ECHO, that's
%.o: %.cpp
    $(ECHO) "[OK]  $@"
    $(QUIET)$(COMPILE.cpp) $(OUTPUT_OPTION) $<

%: $(OBJ)
    $(ECHO) "[OK]  $@"
    $(QUIET)$(LINK.cpp) $(OUTPUT_OPTION) $^ $(LOADLIBES) $(LDLIBS)

You'll need to ensure that your include path is in CXXFLAGS, and you might need target-dependent flags:
CXXFLAGS += $(INC)

tmp/%: CXXFLAGS=$(CXXFLAGS_TEST)

All makefiles should have...
.DELETE_ON_ERROR:

Without this, a failed command could leave a part-written output that a subsequent make believes is up-to-date.
Finally
Here's a tyni tyop:
.PHONY: clean, clear

Lose that , - you've said that clean, is a phony target, not clean as you intended.


Fully parameterized PowerShell function for file removal

I have found a way to use pass string values to switch parameters to Remove-Files function so I have refactored the function ho have two switch parameters.
The new version
function Remove-Files {
    [CmdletBinding(SupportsShouldProcess = $true)]
    [OutputType([PSCustomObject])]
    param (
        [Parameter(Mandatory = $true,
                   Position = 0,
                   ParameterSetName = "FolderPath",
                   ValueFromPipeline = $false,
                   ValueFromPipelineByPropertyName = $true,
                   HelpMessage = "Full folder path in which file/files are to be deleted")]
        [string]
        $FolderPath,

        [Parameter(Mandatory = $true,
                   Position = 1,
                   ParameterSetName = "FileName",
                   ValueFromPipeline = $false,
                   ValueFromPipelineByPropertyName = $true,
                   HelpMessage = "File name that can include wildcard character")]
        [SupportsWildcards()]
        [string]
        $FileName,

        [Parameter(Mandatory = $false,
                   Position = 2,
                   ParameterSetName = "OlderThen",
                   ValueFromPipeline = $false,
                   ValueFromPipelineByPropertyName = $true,
                   HelpMessage = "Number of days to delete files older than that")]
        [int]
        $OlderThen = 0,

        [Parameter(Mandatory = $false,
                   Position = 3,
                   ParameterSetName = "Recurse",
                   ValueFromPipeline = $false,
                   ValueFromPipelineByPropertyName = $true,
                   HelpMessage = "Switch on to file remove files in subfolders")]
        [switch]
        $Recurse = $false,

        [Parameter(Mandatory = $false,
                   Position = 4,
                   ParameterSetName = "Force",
                   ValueFromPipeline = $false,
                   ValueFromPipelineByPropertyName = $true,
                   HelpMessage = "Switch on to force remove files")]
        [switch]
        $Force = $false
    )

    process {
        $FolderSpaceFreed = 0
        $FilesRemoved = 0
        $FailedRemovals = 0

        if (-not (Test-Path -Path $FolderPath)) {
            Write-Log -Message "ERROR: $FolderPath folder does not exist"
            return
        }

        $FullPath = Join-Path -Path $FolderPath -ChildPath $FileName

        if ($Recurse) {
            $FileList = Get-ChildItem -Path $FullPath -Recurse
        }
        else {
            $FileList = Get-ChildItem -Path $FullPath
        }

        $DateToDelete = (Get-Date).AddDays(- $OlderThen)

        $FileList = $FileList | Where-Object {$_.CreationTime -lt $DateToDelete}

        foreach ($File in $FileList) {
            $FileSize  = (Get-Item -Path $File.FullName).Length
            $SpaceFreed = Get-FormattedFileSize -Size $FileSize

            if ($Force) {
                Get-Item -Path $File.FullName | Remove-Item -Force
            }
            else {
                Get-Item -Path $File.FullName | Remove-Item
            }

            if (-not (Test-Path -Path $File.FullName)) {
                $Message = "Successfully deleted " + $File.Name + " file - removed $SpaceFreed"
                $FolderSpaceFreed += $FileSize
                $FilesRemoved ++
            }
            else {
                $Message = "Failed to delete " + $File.Name + " file"
                $FailedRemovals ++
            }
            Write-Log -Message $Message
        }

        $SpaceFreed = Get-FormattedFileSize -Size $FolderSpaceFreed

        if ($FilesRemoved -gt 0) {
            Write-Log -Message "Successfully deleted $FilesRemoved files in $FolderPath folder, and $SpaceFreed of space was freed"
        }
        if ($FailedRemovals -gt 0) {
            Write-Log -Message "Failed to delete $FailedRemovals files in $FolderPath folder"
        }
        if ($FilesRemoved -eq 0 -and $FailedRemovals -eq 0) {
            Write-Log -Message "No files for delition were found in $FolderPath folder"
        }
        New-Object -TypeName psobject -Property @{
            FolderSpaceFreed =  $FolderSpaceFreed
            FilesRemoved = $FilesRemoved
            FailedRemovals = $FailedRemovals
        }
    }
}


Copy function improvements

Your copy function could be better:

   void PLS_copy(PLS *to,PLS *from) {
       int tc = from-> curlen; // chars to copy
       if(tc > to->maxlen) tc = to->maxlen;
       memcpy(to->buf,from->buf,tc);
   }

You could use const on your from argument.
You never update the length of the to string.  I'm assuming this is like a strcpy, so the to string should have its length set to the length that you just copied.

Here is how I would write it:

   void PLS_copy(PLS *to, const PLS *from)
   {
       uint8_t bytesToCopy = from->curlen;

       if (bytesToCopy > to->maxlen)
           bytesToCopy = to->maxlen;
       memcpy(to->buf, from->buf, bytesToCopy);
       to->curlen = bytesToCopy;
   }

Flexible array member

I agree with the comment by M.M about using flexible array members instead of buf[1]:

typedef struct PLS {
   uint8_t maxlen;
   uint8_t curlen;
   char buf[];  // actual allocated size is in maxlen
} PLS;

struct {
    ...
    PLS s1;   // real allocated size: 100
    char s1buf[100];
    PLS s2;  // real allocated size: 64
    char s2buf[64];
    ...
};

Also, you could use a macro to help declare these fields.  Something like this:

#define PLS_FIELD(name, length)  \
    PLS name;                    \
    char name##buf[length]

Then you could define your struct as:

struct {
    ...
    PLS_FIELD(s1, 100);
    PLS_FIELD(s2, 64);
    ...
};

Casting literal

For your literal casting, I would do this:

char lit1[] = "\x05\x05hello";
const PLS *lit1Pls = (const PLS *) lit1;

The const keyword here will prevent you from writing to the literal.  And the cast I used is simpler than the one you used.  I don't see anything objectionable about doing this.


I am going to provide a much more over-the-top strategies to deal with Sudoku rather than outright code snippets so you can try it out on your own.
[Also I am avoiding code-refactor, so that you can focus on Algorithm first, and then we will talk about Code Design, and finally implementation]

However, if you need more explicit help or I am not clear enough, leave a comment, and I would provide more details as needed.

So, the first thing I noticed about your program is that you implement a simple way to select which cell to fill: Find the first empty one, and try filling that.

There is a much more efficient way to do this: find the cell which has only one Value, and fill that first, this will lead you to fill in first few digits of board pretty quickly, and constrain your solution space.

For this: Just iterate over every cell, and store it in dict what are possible values this cell can have.
Naively: A Cell C can have only values which are not available in its row, its column and its box.
This will lead to something like this:

A1 -- {1, 3, 5}
A2 - {1, 6}
A3 - {6}

and so on...

Now, fun fact! You found out that A3 has only one value, so you fill in that. What this means is that you can now remove 6 from A row and 3rd column as well the box, which will further give 1-value cells, and you can repeat this process till there are no 1-value cells are left.

This will give tremendous speed improvements over your current solution.

But we are not done yet!

Moving forward, there are two ways to go:

Improve our function which determines the values for cell. Remember, our naive function was that a cell has values which are not in row, cell and box. But in Sudoku, we apply other logics as well. For example if both A2 and A3 has value of {2, 4}, then we know that no other cell in A row can have value of 2 and 4, and we can remove it. There are several such strategies which can help you out.
This is how Humans solve Sudoku
Next is Computer's way. Now, you already have a solution which is close to this, which is to have a backtracking mechanism. However, instead of selecting cell randomly, select a cell with least possible values to fill in the random value. For example if you have to choose between A2 which has 2 choices and A4 which has 3 possible choices, fill in A2 first.

These will result in very fast Sudoku solvers :)


Encoding and assigning the result to a label

Here is a marginally more concise solution:

cell.titleLabel.text = [NSString stringWithCString:[[item[@"main_tag"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding].capitalizedString;

If I had to do this more than once I would consider hiding this complexity in an NSString category like:

@interface NSString(Utils)
    -(NSString)stringWithLatinEncoding;
@end

@implementation NSString(Utils)

-(NSString)stringWithLatinEncoding
{
     return [NSString stringWithCString:[self cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
}

@end

This will simplify your code to:

cell.titleLabel.text = ((NSString*)item[@"main_tag"]).stringWithLatinEncoding.capitalizedString;


Just be lazy. Don't do what you're told. They'll never know.
Instead of truly increasing the bottom i values right away, just make a note at the i-th value from the bottom to increase it by v when it gets popped. And when that pop happens, move the note to the value below, so it gets increased by v as well (when it gets popped). And so on, so that this will add v to all bottom i values (when they get popped).
To support multiple inc operations: If a value already has a note to add w to it (and all values below it), change that to w + v.
For easier coding, just store all values along with such a note, but with initial adding value 0.
Now all three operations are O(1).
Oh wait. Not quite O(1), since you're using a deque so you can't access an arbitrary index in O(1). That's actually a problem in your solution as well. Your increasing the bottom i values isn't O(i) but only O(i2). If you switch to a list, yours would be O(i) and mine would be O(1). This loses the O(1) of appending/popping to/from a deque, but the list still does them in amortized O(1). So then all three operations are amortized O(1). Alternatively you could keep your deque and store the notes in a separate dict, but then it's O(1) just as much as dict access is O(1) (i.e., not truly, but practically), and I suspect it would be a bit slower than the list version.


I did not understand what exactly are you asking here. Anyway, I will review your code:

First, make the fields private and provide getters when you need to access them. These that are set in constructors and are never re-setted, you may make them final.

Second, the CCConsole class may break if multiple threads access the redirect method at the same time.

Third, the CCConsole.redirect(this); in the LongRunningWorker is bad. There is no way to create a LongRunningWorker for testing purposes that does not interferes with everything else. Further if anything interferes with the CCConsole (which acts as a singleton), there is no way to remove it. I sugesting to make the CCConsole a normal object (i.e. you instantiate it and no more static fields used). In the LongRunningWorker constructor add a CCConsole parameter. In the RealWorker class, get a CCConsole from somewhere (instantiate it, get from a parameter, from a factory method, whatever).

Forth, avoid inheritance if you can using the strategy design pattern. Instead of making LongRunningWorker abstract with the abstract go method to be overriden in the RealWorker subclass, do this:

Create an interface with the go method (lets say LongWork).
Add a parameter to the LongRunningWorker class of the type LongWork, and save it in a field.
In the doInBackground() method, instead of calling the local go() method, call the one from the LongWork object.
LongRunningWorker is not abstract anymore, and you may remove the go() method.
RealWorker does not extends LongRunningWorker anymore, but now implements the LongWork interface.
You may remove the ColorSwingConsole parameter from the RealWorker class.


tl;dr: This is pretty good for a beginner. It’s robust to bad input and plays smoothly. To improve it, you could use functions to make it more reusable, and I’ve suggested a bunch of small ways to tidy up your Python. But a high level it works well.

I’m just going to dive in, run the script, and see what happens. You didn’t provide a words.txt file, so I just used this small sample:

american
captain
dictionary
fish
hangman
letter
list

Comments:

Overall, it seems pretty robust. I was unable to cause a traceback or exception by passing in dodgy input – kudos!

(And yes, I passed in an emoji thumbs-up, and it handled it fine.)
At the risk of getting bludgeoned to death by Jeff Atwood, I found a pluralisation bug:

Try again, you have only 1 lives left!
So far you have used:
['b', 'c', 'd', 'e', 'f', 'i']

Should be “lives”.
The program treats uppercase and lowercase letters as distinct. That’s not what I expect when I play Hangman – at least whenever I’m played it, I’m just guessing letters, not their associated case as well.
There are a few cases where the program just asks for the next letter, and doesn’t give a helpful message. When I guess a letter that I’ve already guessed (correct or not), it goes straight to prompting me for a new letter without explaining why.

That’s more adding polish than fixing a bug – but it would be nice.
I think a newline between guesses would make the output much easier to read. That’s a personal preference though, not a bug.

At a high-level, the problem with this code is that it isn’t very reusable. It’s good to break your code down into functions – that allows it to be reused within the same file, or across other files.

For example, this script only allows me to play a single game of Hangman. Having a play_hangman() function would allow you to keep playing Hangman until the player got bored. Here are some suggestions to get you started:

play_hangman(word, number_of_lives)
get_random_word_from_file(file_path) – letting me specify the file path means I could drop in another word list easily

I think the while loop is fine for this purpose.

Once you have some functions in the file, you should use the if __name__ == '__main__' construction, which allows the same file to be used both as a module and a script. Like so:

if __name__ == '__main__':
    play_hangman('pomegranate', number_of_lives=8)

The code inside that if block only runs if the script is run directly; if you access part of the file via an import statement, it doesn’t run. That means you can import from the file without having to play a game of Hangman first.

Finally, here are some minor line-by-line comments and/or nitpicks:

You’re pretty good for PEP 8 compliance. One line is a bit long, and you need a bit of extra spacing around your comments, but otherwise fine.
The wordlist variable is unused.
When you choose the word, you open the words.txt file, but don't close it again. You could add an explicit close, but a better approach is to use the with keyword when opening files, like so:

with open("words.txt") as wordsfile:
    word = random.choice(wordsfile.readlines())

The length variable is only used twice (and I’m going to get rid of the second usage shortly), so I’d remove it and just use it directly.
The way you’ve constructed the mock_word list is a little strange. You could go straight to it in one line:

mock_word = ['_'] * len(word)

Also note that the word “mock” has a special meaning in programming, so I’d suggest picking a different name for this variable – perhaps player_guess?
Don’t be stingy with variable names – characters are cheap. Names like used_lets and let can become used_letters and guessed_letter. It makes your program easier to read.

Now I’m diving into the heart of the program: the while loop that processes the player guess.

The first if branch is fine. However, you’re only checking that I don’t enter too many characters; you don’t check that I enter enough characters. This loop could be improved by checking for an incorrect number of characters, and printing a generic message:

if len(letter) != 1:
    print("Please enter a single character.")

In the elif branch, a common way to decrement a variable is to write lives -= 1. That’s a bit more compact.

In the print statement telling me how many lives I have left, you’re using the %r token. That’s fairly generic – it just prints the string representation of whatever gets passed in. Since you know that the lives variable is an integer, I think it’s better to use the more explicit token %d. As I read the string, I know what sort of data will appear here.
In the else branch, a more Pythonic approach than iterating over the indexes is to use enumerate(), which iterates over the index and the array element together. Like so:

for i, letter in enumerate(word):
    if guessed_letter == letter:
        player_guess[i] = letter


AdventOfCode Day 1 : find X element matching a criteria in haskell

While the code certainly works, I wouldn't necessarily call it idiomatic. Haskell's safety and robustness stems from its types, and the type signatures are completely missing. Sure, it works fine. However, all integers are Integer by default, a type that has some nice properties (arbitrary large numbers) and some drawbacks (sub par performance compared to Int).
However, to introduce type signatures, we need a function. The third variant introduces a fine candidate: solution.
solution :: Int -> Int
solution n =  foldl1 (*) $ head [ x | x <- sequence $ replicate n inputs , (foldl1 (+) x == 2020 )]

Now that we have a safe foundation and get type errors if we do anything unexpected, let's have a look at the code and the used functions. foldl1 (*) is product and foldl1 (+) is sum, although both alternatives act slightly different on an empty list.. Yes, both functions will use foldr internally, but that is fine. If we are going for strictness, then we want to use foldl1' instead, but that's not necessary with numbers from my experience. Also, sequence . replicate is replicateM (from Control.Monad), and the parentheses around fold1 (+) x == 2020 aren't necessary. Note that hlint will report those changes, too.
So without changing the original algorithm, we end up at
import Control.Monad (replicateM)

inputs :: [Int]
inputs = [ ... ]

solution :: Int -> Int
solution n =  product $ head [ xs | xs <- replicateM n inputs
                                  , sum xs == 2020]

main :: IO ()
main = print $ solution 3

Note that we changed x to xs, as we're not dealing with a single element, but instead with lists. This new variant ticks all the boxes:

it has explicit types on its top-level structures ✔
it uses named variants of folds (product for foldl (*) 1, sum for foldl (+) 0) ✔
it uses typical naming (xs for lists) ✔
it splits functionality into reasonable parts (main and solution) ✔

However, there's nothing wrong with your old variant, as it was semantically equivalent (except for empty intermediate lists). If I was to solve AoC, I would have used a similar script-style Haskell format, except for solution's type; I'd use [Int] -> Int or even [Int] -> Maybe Int instead to interact with map read . lines <$> readFile "inputs". But that's personal preference.
And last but not least: Your choice to use the list monad to easily check all \$n\$ combinations was really nice!


Send daily email alerts of the Bitcoin Price

Define some constants
I'd make some constants and put them at the top of the program because if your program becomes bigger, it'll be harder to change their values:
EMAIL_TIME = '06:30'
SLEEP_TIME = 1
URL = 'https://api.coindesk.com/v1/bpi/currentprice.json'

Never store your credentials in clear-text
Here, you replaced your actual password with a placeholder, but what if you mistakenly commit&push it to your public git repository? More, at the moment I can also take your email and send those nice Viagra emails.
What I usually do is store my credentials in a different config file which is in .gitignore as well (it's not A LOT safer, but at least you can't see them + it adds an extra layer of security anyways).
As an alternative, you can create environment variables to store them there if you'd like.

Error handling
Try to add some exception handling to let the user know if something went wrong with its script. You can even create your own exception class:
class RetrieveUrlException(Exception):
    pass

Which you can then call like this:
...
raise RetrieveUrlException('The URL could not be accessed')


How can I optimize this for speed? (C++)

The best optimization you can do is write code that works.

It makes it infinitely faster:

BYTE step[2] = { 0xAC, 0x723A };

    DWORD num = (blockNum / 0x70E4) * step[2];
                                //    ^^^^^^^   Broken. Undefined behavior.
                                //              The rest of the code is invalid.

Second I don't believe your numbers:

  1 minute, 30 seconds for 300,000 calls.

That's an awfully slow machine. 90 seconds for 300,000 calls or 3,333 calls a second. Even unoptimized this code runs (300,000) in less then 1/100 of a second on my machine when fully optimized it is closer to 1/1000 of a second.

So it is not this code that is causing you to slow down. But the result of this code may be affecting the call path inside your application and causing other more costly code to be executed.

Since this code takes 1/1000 of a second of the 90 second total. It is contributing to 0.0001% of the execution time. This is so insignificant that you should not even be trying to optimize this part of the code.

My test code:

#include <iostream>
#include <time.h>
#include <vector>
#include <algorithm>

int step[2] = { 0xAC, 0x723A };
int packageType = 1;

int computeLevel(int blockNum)
{
    int num = (blockNum / 0x70E4) * step[1]; // changed.
    if (blockNum < 0x70E4)
        return num + step[0];                // changed
    return (1 << packageType) + num;
}

// Add this to pre-vent the code being optimized to zero.
int result = 0;
int check  = 0;
int doComputeLevel(int blockNum)
{
    result += computeLevel(blockNum);
    ++check;
}

int main()
{
    // Set up random test data
    std::vector<int>    data;
    data.reserve(300010);
    for(int loop = 0;loop < 300000;++loop)
    {
        data.push_back(rand());
    }

    // Run the test
    clock_t t = clock();
    std::for_each(data.begin(), data.end(), doComputeLevel);
    clock_t e = clock();

    // print the results;
    std::cout << (e-t) << std::endl;
    std::cout << (e-t)*1.0/CLOCKS_PER_SEC << std::endl;
    std::cout << data.size() << " : " << check << " : " << result << std::endl;
}

> g++ -O3 t.cpp
> ./a.out
1812                           TICKS
0.001812                       TIME in seconds
300000 : 300000 : 62755196     iterations : check of iterations : result


What's the use of presenting even 5,000 records to the user? Do you expect a user to scroll to row 4711, look at "18912,N", and say "Strange, why wasn't there a '12345,N' in row 1234?", or "Interesting, now let's see where the corresponding '54321,X" is to be found!"?

Your GUI should help the user to specify the comparatively small set(s) of records pertinent to his current problem/question; even if working with the data means "check every item in turn", it would be more human to present the records in small batches.

All this points to using your file as a database table bound to the controls of your GUI; then the problem of "reading a .csv fast" completely vanishes.


Sort and source configuration files from one of two directories

You can combine sort -V | uniq into sort -uV.

Note that the -V flag of sort doesn't exist in BSD.
Consider replacing it with -n if that's good enough.

The if inside the loop can be written more compactly as:

[[ -r $HOME/.myapp/$f ]] && source $HOME/.myapp/$f || source /etc/myapp/$f

You could also replace source with . which is equivalent.


Yes you have added enough explicit locks to make it safe (under normal situations).

But it is not exception safe and not written in C++ style. You are writing the code as if it was Java (maybe). Which is causing all sorts of problems.

Why do you need the start() and stop() functions? They provide no utility and they initialize members that should be initialized in the constructor. Also the threads are started before the object is fully initialized and thus you have a thread running in a function when the object is not initialized correctly (and thus will probably immediately exit).

    void start()
    {
        // Soon as you create a thread
        // It starts running. So the next thing that is going to be
        // executed is the function `renderFunc()` which also depends
        // on member 'running' which has not been set.
        renderThread = std::unique_ptr<std::thread>(new std::thread(&Test::renderFunc, this));
        updateThread = std::unique_ptr<std::thread>(new std::thread(&Test::updateFunc, this));
        std::cout << "Threads Created" << std::endl;

        // You already have running threads that depend on this variable.
        // Yet this is the first time you even set it. Your code is already
        // broken.
        running = true;
    }

The next thing is the dynamic creation of the thread objects. Why. There is no need to dynamically create them. They should be automatic variables (ie non pointer members). The problem is that you need to be very careful with the initialization order.

class Test
{
    volatile bool running;
    std::mutex    mutex;
    std::thread   renderThread;
    std::thread   updateThread;
  public:
    Test()
        : running(false) // Make sure this is first.
        , renderThread(&Test::renderFunc, this)
        , updateThread(&Test::updateFunc, this)
    {
        std::cout << "Test starting" << std::endl;
    }
    ~Test()
    {
        std::cout << "Test finished" << std::endl;
        updateThread.join();
        renderThread.join();
    }
    inline void quit()
    {
        running = false;
    }

Next thing is your locking and unlocking of the mutex.

    void updateFunc()
    {
        while(running)
        {
            mutex.lock();
            std::cout << "update" << std::endl;
            mutex.unlock();
        }
    }

This is not exception safe. Any situation were you do:

{
    lock(x);
    work();
    unlock(x);
}

Where lock/unlock is a combination that must be called as a pair. Then you should be using RAII. This is where you have an object where lock() is called in the constructor and unlock() is called in the destructor. This also makes the code exception safe because the destructor will always be called even  if their are exceptions.

{
    LockObject  locker(x);  // calls lock(x)
    work();
}                           // destructor of locker will call unlock(x)

For this simple situation there is no need to create your own type. There is one defined in the standard scoped locked.

    void updateFunc()
    {
        while(running)
        {
            std::lock_guard<std::mutex> locker(mutex);
            std::cout << "update" << std::endl;
        }
    }

Stop using dynamic allocation when you do not need it:

    std::unique_ptr<Test> test = std::unique_ptr<Test>(new Test());

    // Just do this:
    Test    test;


Do you really need to print the answers to screen?

Most time consumed by the program is for printing each result to screen, using a simple counter or just saving all element in a list (should you need to work with the values, but not actually see them) saves a massive amount of time. Compare my results below:

With printing each value to console - your original code: 00:03:16.008651

static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            int n = 15600000;
            int j = n - 1;

            while (j > 1)
            {
                if (GCD(n, j) == 1)
                    Console.WriteLine(j);

                j--;
            }
            sw.Stop();
            Console.WriteLine("Time elapsed: " + sw.Elapsed);
        }

Adding value to list and then printing: 00:03:29.6715458

static void Main(string[] args)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    int n = 15600000;
    int j = n - 1;
    List<int> lst = new List<int>();

    while (j > 1)
    {
        if (GCD(n, j) == 1)
            lst.Add(j);

        j--;
    }

    foreach(int ele in lst)
    {
        Console.WriteLine(ele);
    }

    sw.Stop();
    Console.WriteLine("Time elapsed: " + sw.Elapsed);
}

With counter or list (not printing to console): 00:00:04.5160762

static void Main(string[] args)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    int n = 15600000;
    int j = n - 1;
    int counter = 0;

    while (j > 1)
    {
        if (GCD(n, j) == 1)
            counter++;

        j--;
    }
    sw.Stop();
    Console.WriteLine("Time elapsed: " + sw.Elapsed);
}


The Iterator is a second stage provision for API users. As such I will not comment on it.
The package name should not contain capitals. It is only a convention, but for java it is maintained relatively strict in the community, due to the hundreds of libraries.
Using T[] or rather Object[] requires some disregard to typing. I solved that by passing the class of T: Integer.class or such. Alternatively one could use ArrayList<T> instead of T[]. Then there is full generic typing.
protected is a dubious choice for such a container class, but maybe a next task would be to add functionality in the form of a child class.
Now to the critics:

limit should rather be a parameter in the constructor, made two constructors, one with a default limit. As limit is redundant, equal to array.length you need not have it as field.
You can use final for unchanging fields.
index and pointer are no-names, often unsuited for fields.
No display of really using circularity, start index and end index running around.
Delete in the middle is atypical for a circular array, should not go from 0 to length, and should actually delete 9 in 3 9 5.
Here I represented circularity by a size to distinghuish empty from full, and a start index consumeIndex and an end index produceIndex. Modulo array.length is needed.
findIndex used == but the Object wrappers are hideous: Integer.valueOf(3) == Integer.valueOf(3) (internal cache upto 128) but Integer.valueOf(300) == Integer.valueOf(300). So use equals.

So (not guaranteeing correctness):
import java.lang.reflect.Array;

public class CircularArray<T> {

    public static final int DEFAULT_LIMIT = 5;
    private final Class<T> elementType;
    private final T[] array;
    private int consumeIndex = 0;
    private int produceIndex = 0;
    private int size = 0;

    public CircularArray(Class<T> elementType) {
        this(elementType, DEFAULT_LIMIT);
    }

    public CircularArray(Class<T> elementType, int limit) {
        this.elementType = elementType;
        array = (T[]) Array.newInstance(elementType, limit);
    }

    public void add(T data) {
        if (size == array.length) {
            throw new IllegalStateException("CircularArray is full");
        }
        array[produceIndex++] = data;
        if (produceIndex >= array.length) {
            produceIndex = 0;
        }
        size++;
    }

    public void delete(T data) {
        // 4 5 9 11 1
        // delete 9
        int deleteIndex = findIndex(data);
        if (deleteIndex == -1) {
            return;
        }
        for (int index = deleteIndex; (index + 1) % array.length != produceIndex; ++index) {
            array[index] = array[(index + 1) % array.length];
        }
        produceIndex = (produceIndex - 1 + array.length) % array.length;
        --size;
    }

    private int findIndex(T data) {
        for (int i = 0; i < size; i++) {
            int index = (consumeIndex + i) % size;
            if (array[index].equals(data)) {
                return index;
            }
        }
        return -1;
    }

}

Some test code (as requested by comment)
CircularArray<Integer> ca = new CircularArray<>(Integer.class);
ca.add(1);
ca.add(2);
ca.add(3);
ca.add(4);
ca.add(5);
try {
    ca.add(6);
    throw new IndexOutOfBoundsException("Overflow expected");
} catch (IllegalStateException e) {
    System.out.println("Expected overflow");
}
int i = ca.delete(3);
if (i != 2) {
    throw new IllegalStateException();
}
ca.delete(1);
ca.add(7);
ca.add(8)
int i = ca.findIndex(8);
if (i != 0) {
    throw new IllegalStateException();
}

This is not real testing, more demo, and unit tests are a different thing, with many scenarios. Also note that the code can be optimized, for instance for deleting the first element:
    public void delete(T data) {
        // 4 5 9 11 1
        // delete 9
        int deleteIndex = findIndex(data);
        if (deleteIndex == -1) {
            return;
        }
        // Optimisation:
        if (deleteIndex == consumeIndex) {
            consumeIndex = (consumeIndex + 1) % array.length;
            return;
        }


Preface

I am using Apple Clang 10 and the following commands to build.

clang++ -std=c++17 -fmodules-ts --precompile Lazy.cppm -o Lazy.pcm
clang++ -std=c++17 -fmodules-ts -c Lazy.pcm -o Lazy.o
clang++ -std=c++17 -fmodules-ts -fprebuilt-module-path=. Lazy.o main.cpp

I'm using C++ 17 since that's the tag on the question, although I believe MSVC /std:c++latest corresponds to the parts of C++ 20 that are already implemented on MSVC.

I had one compilation error when I first tried this:

In file included from main.cpp:3:
Lazy.cppm:10:21: error: definition of 'optional' must be imported from module 'Lazy.<global>'
      before it is required
   std::optional<T> m_resource;
                    ^
main.cpp:26:24: note: in instantiation of template class 'gstd::Lazy<Resource>' requested here
   gstd::Lazy<Resource>resx([](){ return Resource(4,5); });

I solved it by adding #include <optional> in main.cpp, but maybe there's a better way.  Please let me know if there is a better solution.  I have only toyed around with modules so I'm far from an expert.

Fix your indentation

Minor nitpick: use consistent indentation.
You have 4 spaces for most of it (which is fine) but 1 space in a few spots.
And 0 spaces in a few spots too.  There are tools that can do this for you automatically (although it's pretty
easy to just do it by hand).

Consider using operator T

C++ can implicitly convert your object into a T:

template <typename T>
struct Lazy {
    operator const T&() {
        ...
    }
};

int main() {
    Lazy<int> n(...);
    return n;
}

Consider making access const

When you access an object, you don't expect to modify it.  In other words, you should be able to write:

Lazy<int> const n(...);
int x = n + 2;

This implies an object that looks something like

template <typename T>
struct Lazy {
    operator const T&() const {
        ...
    }
private:
    std::optional<T> mutable opt;
};

Think about what kind of functions you want to support

As you've written it now, you have two std::functions: the argument to the ctor and the one in the object.  You should at most have one.  You could use std::move.

Lazy(std::function<T()> ctor_func)
    : m_ctor_func(std::move(ctor_func)) // at least do this!
{}

At least use a member initializer list instead of initialization by assignment.

It may be preferable to get rid of std::function completely and instead use a template parameter.
This would allow you to get rid of all the copying.
You could even have non-copyable types in the function object.
You could even go overboard and deduce the stored type based on the templated function.  Then you could just write:

Lazy const n([nc=NonCopyable()]{ return 1; });

No template arguments!  It's up to you to decide whether this is a good idea, but it may be a good exercise if you
are new to templates.

Use optional::emplace

... instead of assignment.


Count complete trips to the basement and back to ground floor

A few points.

if with only the “then” case is usually written with when, which is in general more handy since it allows several forms inside its body. So you could write (when (finished-basement-trip-p floor new-floor) (incf count)).

In a loop you can define variables that change at each iteration with the clause for variable = expression, and this in many cases avoid the use of nested let clauses, that make more difficult to read the program. Another useful iteration clause is for variable = expression1 then expression2, which assigns to variabile the value of expression1 during the first iteration, and in all the others the value of expression2.

In a loop, if you need to count something and then return its value, you can use the “numeric accumulation” clause count, analogous to the sum clause, in which you count how many times a boolean espression is true.

Here is a proposed simplification. Note that in my version I do not use local functions since I think the program is easy enough to read without them. This is just a personal opinion.
(defun count-basement-trips (travel)
  (let ((floor 0))
    (loop for c across travel
          for up = (char= c #\u)
          do (incf floor (if up 1 -1))
          count (and (zerop floor) up))))

Here's the buggy version suggested by @user235906 in a comment that got deleted. @Renzo points out it gives an incorrect answer for the test string "ud":
(defun count-basement-trips (travel)
  (loop for c across travel
        for up? = (char= c #\u)
        for floor = 0 then (incf floor (if up? 1 -1))
        for completed-trip? = (and up? (zerop floor))
        count completed-trip?))

And here's the suggested fix:
(defun count-basement-trips (travel)
  (loop for c across travel
        for up? = (char= c #\u)
        for change = (if up? 1 -1)
        for floor = change then (incf floor change)
        for completed-trip? = (and up? (zerop floor))
        count completed-trip?))


Convert int64 to custom base64 number string

Your solution as given has a few problems.  Firstly, DecodeLogKey doesn't work, as you're ranging over the index of logKey rather than the value of logKey.  Also, the range will start from the first character in the string, and for what you're doing, you need it to start from the last character in the string.

I'd suggest a solution like this:

var codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"

func EncodeLogKey(id int64) string {
    str := make([]byte, 0, 12)
    if id == 0 {
        return "0"
    }
    for id > 0 {
        ch := codes[id%64]
        str = append(str, byte(ch))
        id /= 64
    }
    return string(str)
}

func DecodeLogKey(logKey string) (int64, error) {
    res := int64(0)

    for i := len(logKey); i > 0; i-- {
        ch := logKey[i-1]
        res *= 64
        mod := strings.IndexRune(codes, rune(ch))
        if mod == -1 {
            return -1, fmt.Errorf("Invalid logKey character: '%c'", ch)
        }
        res += int64(mod)
    }
    return res, nil
}

That way you can easily change the character set you're working with, and the code becomes a lot more readable.  It could be made more flexible by using len(codes) as the base rather than assuming it's 64.

You still need to include checks for non-Latin1 UTF-8 characters such as 好 if you want to be really thorough.

In terms of testing for correctness, you should write unit tests (preferably table driven) to be sure that your code is working correctly. Dave Cheney has a good post on Writing table driven tests in Go that you should read.

Play for my solution


How can I make this Euler/RK4 implementation more elegant?

I feel ... that I should be able to use more inbuilt functions (that
  I'm not aware of)

Let me introduce you to your new best friend... Hoogle. Seriously, it's the best thing since sliced... monad analogies. Install a local copy as well.

We're producing a sequence of values by repeated application of a function, so let's search Hoogle for

(a -> a) -> a -> [a]

The first hit is iterate :: (a -> a) -> a -> [a], which looks like a good candidate. But a little further down the page, we see

  until :: (a -> Bool) -> (a -> a) -> a -> a

  until p f yields the result of applying f until p holds.

Bingo. So we know that euler is going to look like

euler :: Fractional a => [[a] -> a] -> ([a] -> Bool) -> a -> [a] -> [a]
euler fs target h = until target step
    where step x = ???

And we fill in the blanks

euler :: Fractional a => [[a] -> a] -> ([a] -> Bool) -> a -> [a] -> [a]
euler fs target h = until target step
    where step x = zipWith (+) x (map (h *) (pam fs x))

A similar transformation can be applied to rk4:

rk4step fs h x = x +. dx
    where k1 = pam fs x
          k2 = pam fs $ x +. map (h / 2 *) k1
          k3 = pam fs $ x +. map (h / 2 *) k2
          k4 = pam fs $ x +. map (h *) k3
          dx = map (h / 6 *) $ k1 +. k2 +. k2 +. k3 +. k3 +. k4
          (+.) = zipWith (+)

rk4 :: Fractional a => [[a] -> a] -> ([a] -> Bool) -> a -> [a] -> [a]
rk4 fs target h = until target (rk4step fs h)

I'm not sure if I'd actually suggest this, but you could also introduce another function, *.:

rk4step fs h x = x +. dx
    where k1 = pam fs x
          k2 = pam fs $ x +. ((h / 2) *. k1)
          k3 = pam fs $ x +. ((h / 2) *. k2)
          k4 = pam fs $ x +. (h *. k3)
          dx = (h / 6) *. (k1 +. (2 *. k2) +. (2 *. k3) +. k4)
          (+.) = zipWith (+)
          (*.) n = map (n *)

Finally, I think that pam would be more readable as a list comprehension

pam :: [a -> b] -> a -> [b]
pam fs x = [ f x | f <- fs ]


Generating a list of powers in Elm up to some limit

Why don't you just use the exponentiation (^) operator? Using that you can omit the recursion at all:

powers : Int -> Int -> Result String (List Int)
powers base limit =
    if base < 0 then
        Err "negative base"
    else
        let size = floor (logBase (toFloat base) (toFloat limit))
        in Ok (List.map (\i -> base ^ i) (List.range 0 size))

There are some functions I used here:

logBase calculates the logarithm of a number with a given base. This can help to calculate the size of the returned list.
List.range : Int -> Int -> List Int generates an Int list where every element increasing by one.


Implementation of Counting Sort using C++

#include <bits/stdc++.h>

You normally shouldn't use this. It includes every standard library header. If you compile without precompiled headers, this would make your compilation time much greater. The recommended practice is to #include just what you need, and if you want to use a precompiled header as well, that's just fine.

class count_sort
{

It is a bit strange to use a class for sorting. That your sort function is in a class implies that there's state, which is unexpected. You could use a namespace.

  std::map<int, int> m;
  std::map<int, int>::iterator it;

This state can easily be moved inside the functions, to the smallest scope possible.

  void counting_sort(std::vector<int>& a){

The name counting_sort is a bit redundant, seeing as it's a member function of a class called count_sort. You could use sort, or even operator(). Other than that, by taking std::vector<int>& as a parameter, you make this sort function not very general. The way the parameters are usually taken for a sort function (in C++) is as an iterator range:

template <typename Iter>
void counting_sort(Iter begin, Iter end) {

If you don't want to use templates, that's fine, but keep in mind that they make it more general.

One other thing to note is that you never change the vector in this function. That's a sign that it should be taken by const& rather than &. However, the expected semantics of a function called sort is that it modifies its parameter so that, after the function is called, the parameter is sorted. It's unusual and unexpected to have to call another function to obtain the output.

For the actual implementation, you can make use of C++11's range-based for loops (aka for-each loops). This:

for(int i=0; i<a.size(); i++)
{
 m[a[i]]++;
}

Becomes this:

// Read as "`for` each `int i` in `a`, ..."
for (int i : a) {
    m[i]++;
}

Putting together my suggestions, without templates, would look something like this:

namespace counting_sort {
    void sort(std::vector<int>& vec) {
        std::map<int, int> count;

        for (int i : vec) {
            ++count[i];
        }

        // modify the parameter; write the values back out
        auto begin = vec.begin();
        for (const auto& pair : count) {
            while (pair->second > 0) {
                *begin = pair->first;
                ++begin;
                --pair->second;
            }
        }
    }
}


Parse python code, for specific pep8 issues

When I copy&paste your code into my editor, it immediately greets me with 50 errors and warnings. To be fair, some of these are duplicates, because I have multiple linters configured. However, well over 20 of those are real. And ironically, at least 6 of those would have been reported by your own code!
PEP8 violations

Maximum line length
Blank lines (after the module docstring before the first method)
Single space around operators
Function names should be lower_snake_case

Missing import
You are missing the import for re.
Missing definitions
You are missing the definitions for issues and code.
Invalid escape sequence
\ is the escape character in string literals, therefore \s is interpreted as an escape sequence, but it is not a valid escape sequence. If you want to have a literal backslash in your string, you need to escape it with another backslash: \\s.
Missing docstrings
All of your functions are missing docstrings.
Naming
regex, regex1, and regex2 are not very descriptive names.
Bugs
S001 should use 72 as the maximum line length for docstrings and comments, and only use 79 for code. Also, there is a problem with PEP8 itself: it limits the line length to 79/72 characters, but it should instead limit the line length to 79/72 columns. There are characters that take up 2 columns, and there are characters that take up 0 columns. Your code uses characters, as specified by PEP8, so it is correct as far as PEP8 is concerned, but columns would make more sense.
S003 will incorrectly flag this:
"""
;
"""

S004 will incorrectly flag this:
" #"

S005 will incorrectly flag this:
"# TODO"


Loop with enclosing items every 'n' steps

One problem with your solution is that it won't print the last closing </div> tag if there are less than $n elements inside the last <div>.

An approach which fixes that problem and also simplifies the conditional logic for deciding when to print the tags is to chunk the array first using array_chunk and then iterate over the chunks. Now we only need one boolean variable to remember which chunks to surround in tags.

function alternate($names, $n, $opening, $closing) {
    $tag = TRUE;
    foreach(array_chunk($names, $n) as $chunk) {
        if($tag) {
            print $opening;
        }
        foreach($chunk as $name) {
            print $name;
        }
        if($tag) {
            print $closing;
        }
        $tag = !$tag;
    }
}


for (auto info : shader_info) -> for (auto const& info : shader_info) to avoid a string copy.

Reading the source file into a string should probably be a separate function.

We should throw an error if the file fails to open. (tellg will return -1 in that case).

I find it's often helpful to output more than one shader object log before stopping compilation (for example, if we have a minor error in the vertex shader, and another one in the fragment shader, we can see and fix both at once, rather than only having the vertex shader error in the log).

e.g.:
GLuint LoadShaders(const std::vector<ShaderInfo>& shader_info) {
    // ...
    bool compiled = true; // flag to indicate overall compile status

    for (auto const& info : shader_info) {
        // ... read file and compile shader

        GLint status;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &status);

        if (status == GL_FALSE) {
            // ... get log string

            // log the error (if you have an existing logging system, or print to std::cerr)
            LogError("glCompileShader() failed for shader object: " + info.file);
            LogError(log);

            compiled = false; // set the overall flag to false
        }
    }

    // and now we throw!
    if (!compiled) {
        glDeleteProgram(program);
        throw std::runtime_error("Shader compilation failed!");
    }

    // ... link program etc. as before
}


An enum that has situationally invalid entries

There are a couple ways I could address that issue, such as creating more blinker getters, but that or switching form an enum to bit based values and building masks for them.

java.util.EnumSet<E> is the piece you are looking for here.

public class Car {
    static enum Direction {
        LEFT, RIGHT
    }

    EnumSet<Direction> turnSignal;

    void setTurnSignal(Direction direction) {
        turnSignal = EnumSet.of(direction);
    }

    void setHazards() {
        turnSignal = EnumSet.of(Direction.LEFT,Direction.RIGHT);
    }

    EnumSet<Direction> getBlinkerStatus() {
        return turnSignal;
    }
}

That said, this probably isn't the right approach.  If you are trying to capture the state of the blinkers, then you should probably be implementing a state machine that tracks what is going on.  A state machine is absolutely what you want if you are worried about the hazards being enabled and disabled when the turn signal is going (as you indicate in your comment).

The straight forward model would be that you have six states - [LEFT,NONE,RIGHT] x [HAZARDS ON, HAZARDS OFF] - with simple transitions between them.

You can hand roll a state machine easily enough, but beware -- it's common for state machines to snowball in complexity, as you learn more about the system you are modeling.  So it might be worth investing in a library like stateless4J, which gives you a DSL for wiring together your state transition diagram.

public class FSM {
    enum State {
        OFF, LEFT, RIGHT, HAZARDS
        // Unimaginitive names for the "hidden" states.
        , HAZARDS_LEFT, HAZARDS_RIGHT
    }

    enum Toggle {
        LEFT, RIGHT, HAZARDS
    }

    static StateMachine<State, Toggle> create() {
        StateMachine<State, Toggle> fsm = new StateMachine<State, Toggle>(State.OFF);
        fsm.configure(State.OFF)
                .permit(Toggle.LEFT, State.LEFT)
                .permit(Toggle.RIGHT, State.RIGHT)
                .permit(Toggle.HAZARDS, State.HAZARDS);
        fsm.configure(State.HAZARDS)
                .permit(Toggle.LEFT, State.HAZARDS_LEFT)
                .permit(Toggle.RIGHT, State.HAZARDS_RIGHT)
                .permit(Toggle.HAZARDS, State.OFF);
        // etc.

        return fsm;
    }
}

Alternatively, you might consider a state machine design where some of these states are substates of others; stateless4j has substate support, but I haven't explored it enough to have an opinion on whether this should apply for your problem.


Profiling results
Using the profiler in Visual Studio, on my machine (Intel Haswell, 4770K) I get a breakdown roughly like this:

unorderedFFT 107ms
rootsOfUnityCalculator 21ms
bitReversal 17ms

So let's improve all of those.
Roots of unity
The N'th roots of unity in the complex plane is a set of equally spaced points on the unit circle. Their coordinates can be calculated using sine and cosine, but an alternative is starting at 1 + 0i and successively applying a small vector rotation to it (alternative view: the first non-trivial root is calculated, and then iteratively raised to the powers of 0, 1, 2 .. N-1). That way, only one pair of sin/cos is necessary (by the way, std::polar can be used to replace such a sin/cos pair with simpler code). A downside is that it may be less precise. It tends to be OK, but it will perturb the results slightly.
For example, like this:
complexVec rootsOfUnityCalculator() {
    complexVec table;
    table.resize(N);

    auto step = std::polar(1.0, -2.0 * PI / N);
    std::complex<double> root = 1.0;
    for (std::size_t k = 0; k < N; k++) {
        table[k] = root;
        root *= step;
    }

    return table;
}

With this, the time it takes has gone down to 7.5ms, so a factor of 2.3, which is certainly significant. This could be done even faster than that by unrolling the loop and removing the dependency between the copies of the loop body, for example if unrolling by 2 then there would be a separate root1 and root2 that are each multiplied by stepSquared so that their calculations are independent (improving instruction-level parallelism). Doing that reduced the time to 6ms.
Bit-reversal permutation
This is a well-studied permutation, because it is of practical interest, namely this exact application. Various more efficient techniques are known, including some variants of "increment a reversed integer". If an integer i and its reverse rev are both available, calculating the next values for both of them is efficiently possible.
Of course i can just be incremented. rev needs some more work, but there is hope: the XOR of an integer and its successor is a "nice mask" consisting of a contiguous range of ones and a contiguous range of zeroes, with no "mess". This results from how, in the increment, the carry goes through the trailing ones, flipping each of them, then finally the first zero that is found is also flipped and the carry is "absorbed" by that zero - so the bits the flipped start at the least significant bit and form a contiguous range. That is relevant because a "nice mask" can be reversed by shifting it, and then XORing rev by it results in a "bit-reversed increment". A variant of that trick is using a trailing-zero-count instruction to find how long the contiguous range of flipped bits is, and then basing a mask directly on that. Let's go with that:
void bitReversal(complexVec& input) {
    std::size_t maskLen = std::countr_zero(unsigned(N));

    // Permute the input
    for (std::size_t j = 0, rev = 0; j < N; j++) {
        if (j < rev)
            std::swap(input[j], input[rev]);
        std::size_t maskLen = std::countr_zero(j + 1) + 1;
        rev ^= N - (N >> maskLen);
    }
}

This uses the very new std::countr_zero from the <bit> header, a C++20 feature. There are other ways to write that too, for example _tzcnt_u64. unsigned(N) is a bit unfortunate, but required for countr_zero, which refuses to work on signed types. Preferably this would be avoided by making N a constant of type size_t instead of #define-ing it, which I recommend anyway.
Using this trick, bitReversal has gone down from taking 17ms to 14ms (additionally, the memory used by the permutation vector is saved). It's a bit better, but nothing as great as improving the calculation of the roots of unity.
This is not the best way to do it. The if corresponds to a badly-predicted branch, and the memory access pattern is semi-random. There are various useful papers about the technique I used here and further improvements, for example practically efficient methods for performing bit-reversed permutation in C++11 on the x86-64 architecture.
The actual FFT
The real meat of the algorithm. Since you asked in the previous question not to bother with suggestions for different algorithms, I won't. However, I can still suggest a performance improvement: use SSE3. SSE2 is actually sufficient, but SSE3 adds the ADDSUBPD instruction which is handy for complex multiplication:
__m128d multiplyComplex(__m128d A, __m128d B)
{
    __m128d ARealReal = _mm_shuffle_pd(A, A, 0);
    __m128d AImagImag = _mm_shuffle_pd(A, A, 3);
    __m128d BRealImag = B;
    __m128d BImagReal = _mm_shuffle_pd(B, B, 1);
    return _mm_addsub_pd(_mm_mul_pd(ARealReal, BRealImag), _mm_mul_pd(AImagImag, BImagReal));
}

Which could be used like this:
void unorderedFFT2(complexVec& input, const complexVec& table) {
    std::size_t k = 2;

    while (k <= N) {
        for (std::size_t r = 0; r < N / k; r++) {
            for (std::size_t j = 0; j < k / 2; j++) {
                __m128d input0 = _mm_loadu_pd((double*)&input[r * k + j + k / 2]);
                __m128d input1 = _mm_loadu_pd((double*)&input[r * k + j]);
                __m128d twiddle = _mm_loadu_pd((double*)&table[N / k * j]);
                __m128d product = multiplyComplex(input0, twiddle);
                _mm_storeu_pd((double*)&input[r * k + j + k / 2], _mm_sub_pd(input1, product));
                _mm_storeu_pd((double*)&input[r * k + j], _mm_add_pd(input1, product));
            }
        }

        k *= 2;
    }
}

Casting those pointers looks scary, but it seems to be allowed according to the paragraph about Array Oriented Access of std::complex. reinterpret_cast could be used if you dislike C-style casts.
Admittedly, using SSE is not very beginner-friendly. But it does help significantly, the time of unorderedFFT went down to 70ms, the biggest improvement in absolute terms.
Using intrinsic functions like this requires including the relevant header, for example #include <tmmintrin.h> (or newer) in this case. Depending on the compiler, it may also require passing certain command line options (GCC and Clang need that, MSVC does not).


Don't search – find. Specifically, don't iterate through all matrix entries for each character. Instead, build a dictionary that maps the characters in the matrix to a pair of indices.

Also, don't loop over indices (in message) unless you have to. Now we have:

position_lookup = dict()
for x in range(len(matrix)):
  for y in range(len(matrix[x])):
    position_lookup[matrix[x][y]] = (x, y)

for char in message:
  if char in position_lookup:
    x, y = position_lookup[char]
    cyphermessage.extend([x, y, " "])

Technically, this behaves different from the code you wrote: consider what happens when one character occurs multiple times in the matrix – I only use the last occurrence, while you append all possibilities.


Recognizing elements and doing event handling for repeating templates

Formatting Improvements

I don't have time for a full review, but I will help with some of these formatting issues.

Quoted sources: Douglas Crockford

1... You've got some invalid code in there. "Quotes" in JavaScript can't span multiple lines.

Invalid:

var html="
Chat Window

<textarea rows='4' cols='50'>  </textarea>
<input type='button' value='send'>
";

Valid:

var html = "
Chat Window

" +
        "<textarea rows='4' cols='50'>  </textarea>" +
        "<input type='button' value='send'>
";

2... Assignment operators, =, should be padded by a space.

Messy:

html="

Neat:

html = "

3... Variable names should be human readable.

Messy:

var e = document.getElementById('chatApp');

Neat:

var chatAppElem = document.getElementById('chatApp');

4... The parentheses of anonymous function literals should have one space of padding on either side.

Messy:

e.addEventListener("click", function(event){

Neat:

e.addEventListener("click", function (event) {

  If a function literal is anonymous, there should be one space between
  the word function and the ( (left parenthesis). If the space is
  omited, then it can appear that the function's name is function, which
  is an incorrect reading. -DC

5... Spaces should only be made in intervals of 4.

Messy:

  var e = document.getElementById('chatApp');
e.addEventListener("click", function(event){
 var chatWindows=document.getElementsByTagName('p');

Neat:

var e = document.getElementById('chatApp');
e.addEventListener("click", function(event){
    var chatWindows=document.getElementsByTagName('p');

  The unit of indentation is four spaces. Use of tabs should be avoided
  because (as of this writing in the 21st Century) there still is not a
  standard for the placement of tabstops. The use of spaces can produce
  a larger filesize, but the size is not significant over local
  networks, and the difference is eliminated by minification. -DC

6... Lines should be no longer than 80 characters.

Messy:

chatWindows[i].innerHTML+= "Chat window {index} says: "+ event.target.previousElementSibling.value+"
";

Neat:

chatWindows[i].innerHTML+= "Chat window {index} says: " +
    event.target.previousElementSibling.value+"
";

  Avoid lines longer than 80 characters. When a statement will not fit
  on a single line, it may be necessary to break it. Place the break
  after an operator, ideally after a comma. A break after an operator
  decreases the likelihood that a copy-paste error will be masked by
  semicolon insertion. The next line should be indented 8 spaces. -DC

7... Comments should be used generously. And remember: "Why" not "How".

Bad Practice:

  var e = document.getElementById('chatApp');
e.addEventListener("click", function(event){
 var chatWindows=document.getElementsByTagName('p');
if(event.target.value=="send"){
    for(var i=0;i<chatWindows.length;++i){
        chatWindows[i].innerHTML+= "Chat window {index} says: "+ event.target.previousElementSibling.value+"
";
    }
    event.target.previousElementSibling.value=null;
}
},false);

Good Practice:

// Trigger a chat window when button is clicked.

var chatAppElem = document.getElementById('chatApp');      // Info about the purpose
chatAppElem.addEventListener("click", function (event) {   // of significant lines
var chatWindows = document.getElementsByTagName('p');      // will be a plus later on.
if(event.target.value == "send"){
    for(var i = 0; i < chatWindows.length; ++i){
        chatWindows[i].innerHTML+= "Chat window {index} says: " +
            event.target.previousElementSibling.value + "
";
    }
    event.target.previousElementSibling.value = null;
}
},false);

  Be generous with comments. It is useful to leave information that will
  be read at a later time by people (possibly yourself) who will need to
  understand what you have done. The comments should be well-written and
  clear, just like the code they are annotating. An occasional nugget of
  humor might be appreciated. Frustrations and resentments will not.

  It is important that comments be kept up-to-date. Erroneous comments
  can make programs even harder to read and understand.

  Make comments meaningful. Focus on what is not immediately visible.
  Don't waste the reader's time with stuff like

  i = 0; // Set i to zero.

  Generally use line comments. Save block comments for formal documentation -DC


Running over a log file to extract log times

You can use regular expressions with re module to speed up parsing dramatically. For example the following code extracts user and time information by using regular expression (note that user[0] == "C" condition also checked by the regexp):

import re
import datetime

match_record = re.compile(r"^[^ ]+ - (C[^ ]*) \[([^ ]+)").match
strptime = datetime.datetime.strptime

f = open("very/big/log", "rb")

for line in f:
    match = match_record(line)
    if match is not None:
        user, str_time = match.groups()
        time = strptime(str_time, "%d/%b/%Y:%H:%M:%S")
        print user, repr(time)

I think you can make it even faster by reading bigger chunks of data and using re.finditer method.
Don't use dictionaries to store information in the obj dictionary. Tuples is the way to go here and if you really need to use names for fields you can use collections.namedtuple. In any case tuples will be faster than dictionaries (and lists) and will take less memory.
Probably if user in obj will be little bit faster than try/except KeyError here. You can check execution times for small code blocks with timeit module.
Check the Python performance tips. For example Avoiding dots... chapter can be relevant for your code.

UPDATE

The following version of the code read bigger chunks of data and using re.finditer (Not sure if it faster or not. Also note the changes in the regexp):

import re
import datetime

iter_records = re.compile(r"^[^ ]+ - (C[^ ]*) \[([^ ]+) .*$", re.M).finditer
strptime = datetime.datetime.strptime

f = open("very/big/log", "rb")

chunk = ""
while True:
    # Probably buffer size can be even bigger
    new = f.read(1048576)
    chunk += new
    end = 0
    for match in iter_records(chunk):
        user, str_time = match.groups()
        time = strptime(str_time, "%d/%b/%Y:%H:%M:%S")
        print user, repr(time)
        end = match.end()
    if end > 0:
        chunk = chunk[end:]
    elif not new:
        break


One thing I can see right off the bat is that you're likely to be selecting more data than you need. A good rule of thumb is to never use SELECT * FROM. Only select the columns that you need for your query.

For example, in your gifts query you could change the query to "SELECT COUNT(*) FROM tbl_Gifts_Sent WHERE FB_ID='". $FB_ID . "'"; and only ever get one row with one field to check. You could then use $row = $statement->fetch(PDO::FETCH_NUM); and examine $row[0] to find out whether there are any rows that match that $FB_ID and use that value for $amountOfGifts. That will save you from loading too much data (all the fields in tbl_Gifts_Sent as well as saving you from looping over a potentially large resultset in PHP (much slower than letting MySQL do the work). Revised full (untested) code below:

//How Many Gifts are there-----------------
    $sqlcommand = "SELECT COUNT(*) FROM tbl_Gifts_Sent WHERE FB_ID='". $FB_ID . "'";

    $statement = $pdo->query($sqlcommand);
    $row = $statement->fetch();

    if (!$row) {
        $amountOfGifts=0;
    } else {
        $amountOfGifts = $row[0];
    }

Also, I don't know where you're getting your query variables like $FB_ID, but it's probably a bad idea to trust them not to be SQL Injection vectors. You should probably be using PDO::prepare to build your statements; that will at least minimise the injection risk.


Skiena's Programming Challenge [UVa ID 10137]- Getting WA

I did not run it (and I do not like to read it, too much abbreviations, wrong variable names, too less formatting), but what about this case:

  3
  1.01
  0.99
  0.99

sum will be 2.99 / 3 = 0.9966666...
roundAmt will be 0.99
ans will be 0
Obviously, it should be 0.01 to fulfill the requirement "so that the net cost to each is the same, to within one cent"

Beside this, please consider the things I mentioned in the beginning. Some concrete examples:

  sum/=numStudents;

This is not a sum anymore, it is the average.

  loopVar1

Take i, this is expected for a loop variable

  numStudents

Could be: number_of_students or numberOfStudents

for(loopVar1=0;loopVar1<numStudents;loopVar1++)

Could be: for (i = 0; i < number_of_students; ++i)

for(loopVar1=0;loopVar1<numStudents;loopVar1++)
            if(nums[loopVar1]<roundAmt)
                ans+=(roundAmt-nums[loopVar1]);

One could discuss if using the short form without brackets is ok for one line statements, but if it spans over multiple lines, please use brackets, even if it is syntactically ok.

what does roundAmt mean?

and so forth.


Verify that a CSV file contains a backup job for every prod job

I take off the last two characters of the job name, and then grep twice for each area, if both are successful it prints a yes at beginning of line, otherwise it is a no.

  Frankly I can't find matching documentation for the ${job%??}. I don't know what the two question marks stand for.

${job%??} takes the last two characters off the value of $job.
The ${parameter%word} syntax is explained in man bash in the Parameter Expansion section.
The valid patterns in word are shell glob patterns.
A ? in shell glob patterns means any single character.
So two ? mean any two characters.

  I tried using grep -q but it did not work.

Saying "it did not work" always invites the question "what happened?".
I'd recommend to eliminate the phrase "it did not work" from your vocabulary.
I guess one of two things happened:

The command gave an error, perhaps grep: invalid option -- 'q'

This can happen if the implementation of grep in your system does not have such option.

The command did not give an error, but output was not suppressed.

This should be impossible, so I suspect a mistake on your part. If we had the exact command you executed, and the input and output, we could probably explain the mistake.

  the > 2>&1 /dev/null did not work either, I had to reverse it to > /dev/null the redirect 2>&1 (as shown).

It's a bit difficult to understand this sentence.
In any case, > 2>&1 /dev/null is invalid syntax.
Perhaps you meant that instead of 2>&1 >/dev/null you had to write >/dev/null 2>&1 to get the desired effect.
Yes the meaning of these two ways are different.
The effect of 2>&1 >/dev/null is that stderr will be written to stdout and the original stdout will be discarded.
The effect of >/dev/null 2>&1 is that both stdout and stderr will be discarded.
This works by thinking of pointer assignments,
I can go into more detail if needed.

  The script works, it is just a clunky way of getting it done. There has to be a better way.

A couple of things can be improved:

If the file /home/first_spreadsheet.txt exists, then grep should not write anything to stderr, so no need to redirect that
It would be better to store repeatedly used values like ${job%??} and /home/first_spreadsheet.txt in helper variables
It's good limit the scope of changing the value of IFS to avoid unintended effects later in the script. You can do that by prefixing the command that needs it, in this example read
To avoid redirecting the output of individual grep commands, you could group them together and redirect the output of the grouping

Putting the above together (and then some),
you could write a bit simpler like this:

path=/home/first_spreadsheet.txt
while IFS=, read area job machine script
do
    job0=${job%??}
    if { grep $job0 "$path" | grep BACKUP && grep $job0 "$path" | grep PROD; } >/dev/null; then
        printf " YES "
    else
        printf " NO "
    fi
    echo "$area $job $machine $script"
done < "$path"


After going through the "co" GitHub code, I was able to remove the extra boilerplate code. I made following changes to improve my code:

Used the "co" promise and return it in my async function. This help to remove the extra "Promise" wrapper code.
To resolve the "co" promise, I returned the "Promise" as per fails/success scenario.
When making call to MongoDB native driver, used ".catch" to catch the error there itself and apply logic.

Following is my final version which is neater and cleaner using the "co" module:
crud.js
'use strict';
const db = require("./dbmanager").db;
const co = require("co");

module.exports = {

  getAllDocuments: (collectionName)=> {
      //return the "co" promise instead of using "Promise" boilerplate code
      co(function*() {
        let docs = yield db.collection(collectionName).find().toArray().catch(function(err) {
        //in case of error, return the custom message and log the error returned by mongodb driver
        console.log('Error occurred to get documents', err);
        return Promise.reject(new Error(`Error occurred to get documents`)); //return the Promise which will be used by "co"
      });
        return Promise.resolve(docs); //return the Promise which will be used by "co"

      });
  }
};

book.js
'use strict';
const dbcrud   = require("./crud");
const co = require("co");
module.exports = {

  getTransactions: (req, res) => {
   //use "co" to make asyn function call without callback
    co(function*() {
      let transactions = yield dbcrud.getTransactions('transactions');
      res.json(transactions);
    }).catch((err) => {
      console.error(`[ERROR:Controller:API:getTransactions]: error`, err);
      res.status(500);
      res.json({error: err.message});
    });
  },

};


Increase performance for this keyup function?

You can rearrange the if/else to be a little more efficient.

You can retrieve the length a little more efficiently.

And, use .delegate() (pre jQuery 1.7) or .on() (jQuery 1.7+) with a selector of a parent object close to the elements.  That will perform much better than .live() for large numbers of elements.

It could look something like this:

$('#bakery').on('keyup', 'input.name', function() {
    var el = $(this);
    var len = this.value.length;

    if (len < 20) {
        el.width('200px');
    } else if (len <= 56) {
        el.width((len * 10) + 'px');
    }
});

If you don't actually need .live() or .on() type behavior, it's even more performant to avoid the need for event propagation and bind the event handlers directly to the input elements themselves so no selector matching must be done on each key event:

$('#bakery input.name').keyup(function() {
    var el = $(this);
    var len = this.value.length;

    if (len < 20) {
        el.width('200px');
    } else if (len <= 56) {
        el.width((len * 10) + 'px');
    }
});

And, then removing the jQuery .width() call would speed it up some more:

$('#bakery').on('keyup', 'input.name', function() {
    var len = this.value.length;

    if (len < 20) {
        this.style.width = '200px';
    } else if (len <= 56) {
        this.style.width = (len * 10) + 'px';
    }
});

You can see this last one working here: http://jsfiddle.net/jfriend00/7Pb8b/


Unroll for loop as macro to make array unmutable

Please also see also the code here: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=574d96b16d82c5816ebc35c5d88acda2

The name of the function u32_to_preformated_vector let me assume I get something else that what I'm actually get. So I think the naming could improve:

the function actually does not return a vector, but an array;
the function does invert the input bits. That's completely invisible in the name.
You might even indicate the bit order you handle the conversion in, as not everybody might expect to get the least significant bit/the least significant nonet first.

Keeping the mutable array, I came to this code:

pub fn u32_to_preformatted_array(image: u32) -> [[u8; 9]; 3] {
    let mut result = [[0u8; 9]; 3];
    let inverted = !image;
    for n in 0..3 {
        let nonet = inverted >> n * 9;
        for m in 0..9 {
            result[n][m] = 1 & (nonet >> m) as u8;
        }
    }
    result
}

I thought it would help if I bind the inverted image to a new name (inverted). That way in the for loop the reader sees that it is a different value to the one that was passed to the function as the argument.

I also converted the single for loop to two nested for loops. While nesting these loops in general might cause performance problems, it does no harm here, as the number of iterations in the inner code keep the same (27). That way I think the index handling is clearer than doing a divide and a remainder to calculate them. It might also make the bit order more obvious.

The initial value of the array can be initialized in a compacter way as all values in it are the same (0u8 in this case).

I don't think having a mutable array inside the function is a big deal. While I very much go for immutability in general, here the context within which mutation is possible is quite limited. As this is the place where the value gets built, there is no danger of it being used at a different place. From the point you return the value, it will be immutable by the declaration of your function.

I was also trying to get rid of this single mut by using iterators. It's quite easy as long as you change the return type of the function from arrays to vectors:

pub fn u32_to_preformatted_vec(image: u32) -> Vec<Vec<u8>> {
    let inverted = !image;
    (0..3)
        .map(|i| (inverted >> 9 * i) & 0b111_111_111) // `&` not strictly needed
        .map(|nonet| (0..9).map(|i| 1 & (nonet >> i) as u8).collect())
        .collect()
}

In general I have the impression working in a map/reduce style works a lot better with Vec than on arrays. You can also convert the Vec to a slice, but the conversion to an array is harder and often is done using functions like .clone_from_slice() which require a previously allocated array that is mutable again. I also tried to get a slice for the Vec and then use the TryFrom trait to convert it to an array. While I got this working for single dimensional array, I didn't get it to work for the multidimensional array [[u8; 9]; 3].

There is also rarely a need to go from a Vec to an array when designing the solution. Vec is just a little bit of code around an array (that's why to can get a slice from it so easily). So you don't really save anything when using an array.

Thinking about the whole problem as such, I wonder what's the reason for this conversion. You're blowing a 4 byte value up to using 27 bytes of memory. That way you increase the memory usage of your program, and I don't know what you get for it. I don't think that it will actually improve performance because you loose locality when accessing the data. The caching in your computer will not work as good as by using the original 4 byte value.

If the goal you try to get from the conversion is improved readability, I think you might try to define helper functions to get (or set) the individual bits. The calculations are actually quite easy, are performed in the CPU registers and can be inlined by the compiler. That should be quite fast … faster than converting the data to this two dimensional array which requires a lot of access to the computer's memory because it cannot be done in registers.


all of your indentation makes it very difficult to read the code, this is what your code should look like.  you were also missing a Semi-Colon after return false

$.fn.vishTrunc = function(options) {
    var settings = $.extend({
            size: 100,
            omission: '...',
        }, options);

    return this.each(function() {
        var elements = $(this),
            regex    = /\s+/,
            init     = function() {
                elements.each(function() {
                    var textDefault = $(this).text();
                    if (textDefault.length > settings.size) {
                        var words = textDefault.trim().split(regex).slice(0,settings.size);
                        var replacement = $("<p class='replacement'/>").text(words.join(" ") + settings.omission);

                        $(this).parent().find('.read-more').click(function(){
                            if($(this).text() === 'Read More'){
                                replacement.hide();
                                $(this).parent().find('p:eq(1)').show();
                            } else if($(this).text() === 'Read Less'){
                                replacement.show();
                                $(this).parent().find('p:eq(1)').hide();
                            }

                            $(this).text(function(i,old){
                                return old==='Read More' ?  'Read Less' : 'Read More';
                            });

                            return false;
                        });

                        $(this).before(replacement);
                        $(this).hide();

                    }
                });
            };
        init();
    });
};

Personally, I think this is a lot of indentation and a lot of nested functions.

I think that you should break out the functions, this would reduce the amount of nesting and help document what each function is doing by giving them names.